state和props的区别__react
首先说明: state和props是每个组件都有的 如下所示: state修改后会渲染当前组件 class ParentComponent extends React.Component{
constructor(props){
super(props)
this.state = {boolean: true}
this.toggleBool = this.toggleBool.bind(this)
}
toggleBool(){
let istrue = this.state.boolean
this.setState({boolean: !istrue})
}
render(){
return(
<div>
<p>{this.state.boolean? "真": "假"}</p>
<botton onClick={this.toggleBool}>切换状态</button>
</div>
)
}
}
export default ParentComponent
如下所示: props修改后会渲染子组件 class ChildComponent extends React.Component{
constructor(props){
super(props)
}
render(){
return(
<h3>{this.props.boolean? "么么哒": "呵呵哒"}</h3>
)
}
}
class ParentComponent extends React.Component{
constructor(props){
super(props)
this.state = {boolean: true}
this.toggleBool = this.toggleBool.bind(this)
}
toggleBool(){
let istrue = this.state.boolean
this.setState({boolean: !istrue})
}
render(){
return(
<div>
<p>{this.state.boolean? "真": "假"}</p>
<botton onClick={this.toggleBool}>切换状态</button>
<ChildComponent boolean={this.state.boolean} />
/*这个boolean就是props*/
</div>
)
}
}
export default ParentComponent
综上所述,也就不难理解这两者之间的区别了. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |