黑色框为父,绿色框为子,红色框为孙子。父向子孙传值用props;子孙向父传值,要在父设置接收函数和state,同时用props将函数名传入子孙。(总的来说就是给子组件传入父组件的方法,在子组件中调用)
//孙子组件
var Grandson = React.createClass({
render: function(){
return (
<div style={{border: "1px solid red",margin: "10px"}}>{this.props.name}:
<select onChange={this.props.handleSelect}>
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
)
}
});
//子组件
var Child = React.createClass({
render: function(){
return (
<div style={{border: "1px solid green",margin: "10px"}}>
{this.props.name}:<input onChange={this.props.handleVal}/>
<Grandson name="性别" handleSelect={this.props.handleSelect}/>
</div>
)
}
});
//父组件
var Parent = React.createClass({
getInitialState: function(){
return {
username: '',
sex: ''
}
},
handleVal: function(value){
this.setState({username: value});
},
handleSelect: function(value) {
this.setState({sex: value});
},
render: function(){
return (
<div style={{border: "1px solid #000",padding: "10px"}}>
<div>用户姓名:{this.state.username}</div>
<div>用户性别:{this.state.sex}</div>
<Child name="姓名" handleVal={this.handleVal} handleSelect={this.handleSelect}/>
</div>
)
}
});
React.render(
<Parent />,
document.getElementById('test')
);