實現父子組件雙向數據傳遞:
1,(父 ---> 子)父組件可以向子組件傳遞props,props中帶有初始化子組件的數據,還有回調函數。
2,(子 ---> 父)子組件通過調用父組件傳遞到子組件的方法向父組件傳遞數據。
PS:更改props值是不能觸發重新渲染的,只有調用setState纔會觸發控件的重新渲染,所以要實現React的父子組件之間的通訊,需要同時結合props與state來完成,eact是單向數據流,父組件可以向子組件傳遞props。
var Parent = React.createClass({
getInitialState: function() {
return {
name: this.props.name
}
},
onChangeName: function(name) {
this.setState({name: name})
},
render: function() {
return <div onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut}>
Hello 
<Child name={this.state.name} onChangeName={this.onChangeName}>
</Child>
, welcome.
</div>;
},
onMouseOver: function() {
this.setState({
name: "Emily"
});
},
onMouseOut: function() {
this.setState({
name: "Grace"
});
}
});
var Child = React.createClass({
render: function() {
return <span onClick={this.handleClick}>{this.props.name}</span>;
},
handleClick: function() {
this.props.onChangeName("Chris");
}
});
ReactDOM.render(
<Parent name='Anna' />,
document.getElementById('example')
);