我是刚接触React的新手,并试图将我从ParentComponent内部的用户输入(通过输入框)获取的值传递到其ChildComponent中-我将使用用户输入值来运行AJAX呼叫.
我以为通过替换ParentComponent中的状态可以工作-但我仍然无法在ChildComponent中获取它.
我还只希望ChildComponent仅在从ParentComponent接收到输入值后才运行/渲染(这样我就可以运行AJAX调用,然后渲染…).
有小费吗?
var ParentComponent = React.createClass({
getinitialState: function() {
return {data: []};
},
handleSearch: function(event) {
event.preventDefault();
var userInput = $('#userInput').val();
this.replaceState({data: userInput});
},
render: function() {
return (
<div>
<form>
<input type="text" id="userInput"></input>
<button onClick={this.handleSearch}>Search</button>
</form>
<ChildComponent />
{this.props.children}
</div>
);
}
});
var ChildComponent = React.createClass({
render: function() {
return <div> User's Input: {this.state.data} </div>
}
});
解决方法:
您应该将父状态作为道具传递给孩子:将父渲染中的childcomponent更改为:
<ChildComponent foo={this.state.data} />
然后,您可以通过this.props.foo在ChildComponent内部访问它.
说明:在ChildComponent内部,this.state.someData引用ChildComponent状态.而且您的孩子没有状态. (顺便问一下)
另外:this.setState()可能比this.replaceState()更好.
更好地初始化父状态
return { data : null };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。