如何将数据从孩子传递给父母?
问题描述:
我有一种情况,我想增加孩子的父母价值。如何将数据从孩子传递给父母?
父comonent:
getInitialState :function(){
return {counter:0}
},
render(){
<CallChild value={this.state.counter}/>
子组件: render(){ this.props.counter++;}
有什么建议?甚至有可能做这样的事情。
答
您可以创建方法(这将改变父状态)父组件并调用它的孩子像这样
var CallChild = React.createClass({
render(){
return <div>
<h1>{ this.props.value }</h1>
<button onClick={ this.props.onClick }>+</button>
</div>
}
});
var Parent = React.createClass({
getInitialState: function() {
return { counter: 0 }
},
handleIncrement: function() {
this.setState({ counter: this.state.counter + 1 });
},
render(){
return <div>
<CallChild onClick={ this.handleIncrement } value={this.state.counter} />
</div>
}
});