React-菜鸟学习笔记(二)
这篇新颖的东西是React的组件的封装和引用
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js">script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js">script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js">script>
head>
<body>
<div id="example">div>
<script type="text/babel">
/*jsx允许在模板中插入数组,数组会自动展开所有成员*/
/**
var arr = [
白
,
富
,
美
,
甜
];
var element = (
Hello, world!
{arr}
)
ReactDOM.render(
element,
document.getElementById('example')
);
*/
/* React组件 封装一个输出为‘hello world’的React组件,组件名为HelloMessage*/
/*Tips: 原生HTML元素名以小写字母开头,而自定义的React类名以大写字母开头。组建类只能包含一个顶层标签 return hello world
是错的*/
/*方法1 使用函数定义一个组件 方法2 使用ES6 class定义一个组件*/
/**
function HelloMessage(props){
return hello world: {props.name}
}
class Welcome extends React.Component{
render(){
return welcome slowcity
;
}
}
const element =
ReactDOM.render(
element,
document.getElementById('example')
);
*/
/*复合组件 直白点就是封装组件*/
/**
function Name(props) {
return 网站名称:{props.name}
;
}
function Url(props) {
return 网站地址:{props.url}
;
}
function Nickname(props) {
return 网站小名:{props.nickname}
;
}
function App() {
return (
);
}
const element =( )
ReactDOM.render(
element,
document.getElementById('example')
);
*/
/*将生命周期方法添加到类中 挂载和卸载*/
/*
Tips:
()=>this.tick() 是 ES6 中声明函数的一种方式,叫做箭头函数表达式,引入箭头函数有两个方面的作用:更简短的函数并且不绑定 this。
var f = ([参数]) => 表达式(单一)
// 等价于以下写法
var f = function([参数]){
return 表达式;
}
箭头函数的基本语法:
(参数1, 参数2, …, 参数N) => { 函数声明 }
(参数1, 参数2, …, 参数N) => 表达式(单一)
//相当于:(参数1, 参数2, …, 参数N) =>{ return 表达式; }
// 当只有一个参数时,圆括号是可选的:
(单一参数) => {函数声明}
单一参数 => {函数声明}
// 没有参数的函数应该写成一对圆括号。
() => {函数声明}
*/
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
//添加定时器 生命周期钩子 当 Clock 的输出插入到 DOM 中时,React 调用 componentDidMount() 生命周期钩子
componentDidMount(){
this.timerID = setInterval(
() => this.tick(),1000
);
}
//移除定时器 一旦 Clock 组件被从 DOM 中移除,React 会调用 componentWillUnmount() 这个钩子函数
componentWillUnmount(){
clearInterval(this.timerID);
}
tick(){
this.setState({
date:new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<FormattedDate date={this.state.date}/>
<h2>hello{this.props.name} 现在是 {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
Clock.defaultProps={
name:"慢城"
}
function FormattedDate(props) {
return <h2>现在是 {props.date.toLocaleTimeString()}.</h2>;
}
ReactDOM.render(
<Clock />,
document.getElementById('example')
);
script>
body>
html>