React-父子组件传值-子传父
1.直接上代码:
class Children extends React.Component {
constructor(props){
super(props);
this.state={
msg:'我是子组件',
pmsg:this.props.pmsg
}
}
send(){
this.props.handle(this.state.msg); //利用父组件传进来的回调函数改变父组件内的state值,从而实现子到父组件的数据传递
}
render(){
return (
<div className='children'>
<h1>{this.state.msg}</h1>
<p>{this.state.pmsg}</p>
<button onClick={(e)=>{this.send(e)}}>点击发送数据到父组件</button>
</div>
)
}
}
class Parent extends React.Component {
constructor(props){
super(props);
this.state={
msg:'我是父组件的数据',
cmsg:''
}
}
changeMsg(data){
this.setState({
cmsg:data
})
console.log(data);
}
render(){
return (
<div className='parent'>
<h1>{this.state.msg}</h1>
<p>{this.state.cmsg}</p>
<Children handle={(data)=>{this.changeMsg(data)}} pmsg={this.state.msg} />
</div>
)
}
}
ReactDOM.render(
<Parent />,
document.getElementById('app')
)
将父组件内的方法,通过子组件的自定义属性的方式传入,如上:handle={(data)={this.changeMsg(data)}}
在子组件中,通过在方法内使用this.props.handle(data);将子组件内的数据作为参数传入该回调函数,从而实现子传父的实现。