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


黑色框为父,绿色框为子,红色框为孙子。父向子孙传值用props;子孙向父传值,要在父设置接收函数和state,同时用props将函数名传入子孙。(总的来说就是给子组件传入父组件的方法,在子组件中调用)

react子组件如何向父组件传值_第1张图片

复制代码
var Grandson = React.createClass({
    render: function(){
        return (
            
"1px solid red",margin: "10px"}}>{this.props.name}: <select onChange={this.props.handleSelect}> select>
) } }); var Child = React.createClass({ render: function(){ return (
"1px solid green",margin: "10px"}}> {this.props.name}:this.props.handleVal}/> "性别" handleSelect={this.props.handleSelect}/>
) } }); var Parent = React.createClass({ getInitialState: function(){ return { username: '', sex: '' } }, handleVal: function(event){ this.setState({username: event.target.value}); }, handleSelect: function(event) { this.setState({sex: event.target.value}); }, render: function(){ return (
"1px solid #000",padding: "10px"}}>
用户姓名:{this.state.username}
用户性别:{this.state.sex}
"姓名" handleVal={this.handleVal} handleSelect={this.handleSelect}/>
) } }); React.render( , document.getElementById('test') );

你可能感兴趣的:(React)