用 function 创造 component (无状态组件)
function Clock(props){
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {props.date.toLocaleTimeString()}.</h2>
</div>
);
}
function tick() {
ReactDOM.render
ReactDOM.render(<Clock/>, document.getElementById('root'));
);
}
setInterval(tick, 1000);
用 Class 创造 component
State 只能存在于用Class 创造 component里
class Clock1 extends React.Component{
render(){
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
function tick() {
ReactDOM.render(
<Clock1 date={new Date()}/>,
document.getElementById('root')
);
}
setInterval(tick, 1000);
React LifeCycle Method
componentDidMount() {} //第一次render后会call
componentWillUnmount() {} // 马上unmount 用于回收资源等
Do Not
Modify State Directly
this.state.comment = 'Hello'; // Wrong 只能在constractor里 state = " xxx "
this.setState({comment: 'Hello'}); // Correct
//并不是立即执行 是一个异步的布置任务
// setState()---------render()之间运行
this.setState({
counter: this.state.counter + this.props.increment,
}