react子组件如何向父组件传值

前端之家收集整理的这篇文章主要介绍了react子组件如何向父组件传值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

转自:http://blog.csdn.net/qizhiqq/article/details/52384554

黑色框为父,绿色框为子,红色框为孙子。父向子孙传值用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(){
        1px solid green"}}>
                {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(event){
        this.setState({username: event.target.value});
    },handleSelect: function(event) {
        this.setState({sex: 1px solid #000"}}>
                <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')
);

猜你在找的React相关文章