美文网首页
react子组件向父组件传值

react子组件向父组件传值

作者: 街角仰望 | 来源:发表于2018-04-11 15:33 被阅读3302次

    黑色框为父,绿色框为子,红色框为孙子。父向子孙传值用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')
    );
    

    参考:https://blog.csdn.net/qizhiqq/article/details/52384554

    相关文章

      网友评论

          本文标题:react子组件向父组件传值

          本文链接:https://www.haomeiwen.com/subject/fgkplxtx.html