<div id="out"></div>
<script type="text/babel">
// 子传父 父组件获取子组件数据
//父组件传递一个可以改变自己状态的方法给子组件,子组件通过调用父组件传过来的方法来改变父组件的数据。
var Father = React.createClass({
getInitialState:function(){
return{
res:""
}
},
setVal:function(val){ //1.父组件定义一个改变自己状态的方法(setVal),获取子组件传递值之后重新赋值
this.setState({
res:val
})
},
render:function(){//2.通过属性(value)传给子组件
return(
<div>
<h1>父组件</h1>
父组件获取子组件值-->{this.state.res}
<hr/>
<Child value={this.setVal}/>
</div>
)
}
});
var Child = React.createClass({
childChange:function(){ //3.子组件定义改变数据的方法,
var str = this.refs.inputVal.value;
this.props.value(str); //4.把改变的数据传递给父组件,
},
render:function(){
return(
<div>
<h1>子组件</h1>
<input type = "text" ref = "inputVal" onChange = {this.childChange} />
</div>
)
}
});
ReactDOM.render(<Father/>,document.getElementById("out"));
</script>