React专题4: 组件间通信
2020-02-07 本文已影响0人
ImmortalSummer
父控件 传值 给子控件, 父控件可以将值 赋给子控件的一个属性(属性赋值)
子控件 传值 给父控件, 需要父控件将自己的回调函数绑定给子控件, 子控件通过回调这个函数, 将 值以参数的形式传给父控件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="./bower_components/react/react.development.js"></script>
<script src="./bower_components/react/react-dom.development.js"></script>
<script src="./bower_components/babel/browser.js"></script>
<!--
子组件 ==值==> 父组件 属性
父组件 ==值==> 子组件 回调函数
-->
<script type="text/babel">
class Child extends React.Component{
constructor(...args){
super(...args);
this.childName = "小狗"
this.props.fn(this.childName);
}
render() {
return <div className='child'>this is child div, 接收到的父组件入参: {this.props.parameterFromFather}</div>
}
}
class Father extends React.Component{
constructor(...args){
super(...args);
this.fatherName = "大狗"
this.state = {
parameterFromChild:''
}
}
//这个函数绑定到子类控件, 子类控件可以通过 this.props.**(入参) 来回调这个函数, 得以将子控件的变量传到父组件当中来
f_parameterFromChild(parameter){
console.log("接收到从子组件传入参数", parameter);
this.setState({
parameterFromChild:parameter
});
}
render() {
return <div className='father'>...this is father div
<Child parameterFromFather={this.fatherName} fn={this.f_parameterFromChild.bind(this)}/>
接收到的子组件入参:{this.state.parameterFromChild}
</div>
}
}
window.onload = function(){
ReactDOM.render(
<Father/>,
document.getElementById('div1')
)
}
</script>
<style>
.father{
width: 400px;
height: 200px;
background-color: tomato;
}
.child{
width: 360px;
height: 40px;
line-height: 40px;
background-color: teal;
margin: 20px;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
效果如图:
组件间传值.png