React初学习
将一个元素渲染为DOM
ReactDOM.render(
<h1>hello,world</h1>,
document.getElementById("root")
)
React元素是不可变对象
使用函数定义组件
function HelloWorld(props) {
return <h1>hello,{props.name}</h1>
}
使用ES6的Class定义组件
class Welcome extends React.Component {
render() {
return <h1>heelo,{this.props.name}</h1>
}
}
props不能在自身组件中修改
使用state
class CLock extends React.Component {
constructor(props) {
super(props);
this.state={
date:new Date()
};
}
render() {
return (
<h1>data:{this.state.toLocaleTimeString()}</h1>
)
}
}
使用this.setState()更新组件state
this.setState({data:new Date()})
若根据state和props更新state时,this.state和this.props可能会异步更新,使用函数更新state
this.setState((state,props)=>({
counter: state.counter+props.increament
}))