constructor(props) {
super(props);
this.state = {
form:this.props.form
};
}
<p>{this.props.form.name}</p>
为啥我这里子组件初始化通过pros获取父组件数据
当我子组件调用父组件事件改变数据后 子组件的值
name还能被改变 初始化方法不是只执行一次么
当我有两个组件A 和 B A组件调用父组件方法 父组件数据改变
触发B组件数据更新操作时 A组件按上面的写法 数据正常传递
B组件不行 B组件通过componentWillReceiveProps()方法才可更新数据
父组件
class ComModal extends React.Component{
constructor(props) {
super(props);
this.state = {
form:{
},
show:false
};
}
showChange(){
that.setState({
show:true
})
}
render(){
return(
<div>
<A cbclick={e=>that.showChange()}/>
<B show={that.state.show}/>
</div>
)
}
}
A组件
class A extends React.Component{
调用showChange()
}
B组件
class B extends React.Component{
constructor(props) {
super(props);
this.state = {
show:this.props.show //这样的话A改变show后 render里不会改变
};
}
componentWillReceiveProps(nextProps){
这里可以
}
render(){
return (
<p>{that.state.show?'展示':'隐藏'}</p>
)
}
}
父组件通过props传递数据给子组件,props变化,子组件获取到的数据也会变化的,有个属性变化的函数可以侦测到