react项目中,一般子组件负责数据的展示,父组件负责传递数据给子组件
父组件向子组件传值
父组件通过props向子组件传值,子组件通过this.props接收
例如:
#####父组件
class App extends React.Component{
state = {
msg :"父数据",
sonMsg:"-"
}
getSonMsg(data){
this.setState({sonMsg:data})
}
render(){
return (
<div className="App">
<header className="App-header">
<h3>这是父组件</h3>
<div style={{height:"100px",width:'100px',background:'green'}} ref="d1"></div>
<input type="button" value="按钮" onClick={
this.handle.bind(this)
}/>
</header>
<Son getSonMsg={this.getSonMsg.bind(this)}/>
<h3>{this.state.sonMsg}</h3>
</div>
);
}
}
子组件向父组件传值
子组件拿到父组件传递下来的函数,并执行该函数(向函数中传递相应的参数),父组件中传递下来的函数执行后会将子组件向父组件传递的数据保存到state中
class Son extends React.Component{
state = {
msg :"子数据"
}
render(){
console.log("子组件挂载中")
return (
<div>
<h3>子组件</h3>
<input type="button" value="修改子数据" onClick = {
()=>{this.setState({
msg:"修改后的子数据"
})
console.log(new Date().toLocaleTimeString())
}
}/>
<input type="button" value="传值给父组件" onClick={this.props.getSonMsg.bind(null,this.state.msg)}/>
<h3>{this.state.msg}</h3>
</div>
)
}
}