[英]How to pass value from parent component to child component (react)
I'm new to learning React, and am trying to pass on a value that I'm getting from user input inside of my ParentComponent
(via input box) into its ChildComponent
- which I'll use the user input value to run an AJAX call. 我是学习React的新手,我正在尝试将我从
ParentComponent
用户输入(通过输入框)获取的值传递到其ChildComponent
- 我将使用用户输入值来运行AJAX呼叫。
I thought that by replacing the state in the ParentComponent
would work - but I'm still not able to grab it in the ChildComponent
. 我认为通过替换
ParentComponent
的状态会起作用 - 但我仍然无法在ChildComponent
获取它。
I also only want the ChildComponent
to run/render only after receiving the input value from the ParentComponent
(so that I can run the AJAX call and then render...). 我也只希望
ChildComponent
只在从ParentComponent
接收输入值后运行/渲染(这样我才能运行AJAX调用然后渲染...)。
Any tips? 有小费吗?
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>
}
});
You should pass parent state as a prop to your child: Change your childcomponent inside parent render to: 您应该将父状态作为道具传递给您的孩子:将父渲染中的子组件更改为:
<ChildComponent foo={this.state.data} />
And then you can access it inside ChildComponent through this.props.foo
. 然后你可以通过
this.props.foo
在ChildComponent中访问它。
Explanation: Inside ChildComponent, this.state.someData
refers to ChildComponent state. 说明:在ChildComponent内部,
this.state.someData
引用ChildComponent状态。 And your child doesn't have state. 而你的孩子没有州。 (Which is fine by the way)
(顺便说一句,这很好)
Also: this.setState()
is probably better than this.replaceState()
. 另外:
this.setState()
可能比this.replaceState()
更好。
And better to initialize parent state with 最好用初始化父状态
return { data : null };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.