- 父组件传子组件
class Son extends Component {
constructor(props) {
super(props);
this.state = {
name: 'son'
};
}
clickBtn() {
this.props.callBack(this.state.name);
}
render() {
return (
<div>
<div>name:{this.props.name}</div>
<button onClick={this.clickBtn.bind(this)}>改变名称</button>
</div>
);
}
}
class Father extends Component {
constructor(props) {
super(props);
this.state = {
name: 'father'
};
}
callBack(name) {
this.setState({ name: name });
}
render() {
return (
<div>
<Son name={this.state.name} callBack={this.callBack.bind(this)} />
</div>
);
}
}
2.子组件传父组件
class Son extends Component {
constructor(props) {
super(props);
this.state = {
name: 'son',
msg: 'Son Message'
};
this.sendMsg = this.sendMsg.bind(this);
}
clickBtn() {
this.props.callBack(this.state.name);
}
// 在子组件中通过this.props获取修改父组件的方法
sendMsg() {
this.props.msgFromChild(this.state.msg);
}
render() {
return (
<div>
<div>name:{this.props.name}</div>
<button onClick={this.clickBtn.bind(this)}>改变名称</button>
<br />
<button onClick={this.sendMsg}>发送信息</button>
</div>
);
}
}
class Father extends Component {
constructor(props) {
super(props);
this.state = {
name: 'father',
msg: ''
};
}
callBack(name) {
this.setState({ name: name });
}
// 通过子组件中传递过来的msg对父组件state的msg进行修改
msgFromChild(msg) {
this.setState({
msg: msg
});
}
render() {
return (
<div>
<div>Msg: {this.state.msg}</div>
<Son
name={this.state.name}
callBack={this.callBack.bind(this)}
msgFromChild={this.msgFromChild.bind(this)}
/>
</div>
);
}
}