黑色框为父,绿色框为子,红色框为孙子。父向子孙传值用props;子孙向父传值,要在父设置接收函数和state,同时用props将函数名传入子孙。问题来了我不想直接传值给上级,想在姓名后面加“@china”,性别后面加“人”。请看下一篇
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(event){ this.setState({username: event.target.value}); }, handleSelect: function(event) { this.setState({sex: event.target.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‘) );
时间: 2024-11-07 11:15:33