主要是在子组件中加上监听时间(子组件中添加一个生命周期函数)componentWillReceiveProps(nextProps){}
例子:
父组件
import React from 'react';
export default class Parent extends React.Component{
constructor(props){
super(props);
this.state={
msg:"父组件"
}
}
render(){
return(
<div>
<div onClick={()=>{this.setState({mag:"改变msg"})}}>改变父组件msg</div>
<Child data={this.state.msg}></Child>
</div>
)
}
}
子组件
import React from 'react';
export default class Child extends React.Component{
constructor(props){
super(props);
this.state={
childMsg:this.props.data
}
}
//重点部分 目前不推荐使用
componentWillReceiveProps(nextProps) {
this.setState({childMsg: nextProps.data});
}
render(){
return(
<div>
<div >{this.state.childMsg}</div>
</div>
)
}
}
// 如果只是简单的传参
export default class Child extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div>
<div >{this.props.data}</div>
</div>
)
}
}