问题描述
如何在另一个组件中访问一个组件的状态?下面是我的代码,我试图在组件 b
中访问组件 a
的状态。
How do I access one component's state in another component? Below is my code and I'm trying to access the state of component a
in component b
.
var a = React.createClass({
getInitialState: function () {
return {
first: "1"
};
},
render: function () {
// Render HTML here.
}
});
var b = React.createClass({
getInitialState: function () {
return {
second: a.state.first
};
},
render: function () {
// Render HTML here.
}
});
但我没有得到任何东西。
But I'm not getting anything.
推荐答案
即使您尝试这样做,也不是正确的方法来访问州
。最好有一个父组件,其子组件 a
和 b
。 ParentComponent
将保持状态
并将其作为道具传递给子项。
Even if you try doing this way, it is not correct method to access the state
. Better to have a parent component whose children are a
and b
. The ParentComponent
will maintain the state
and pass it as props to the children.
例如,
var ParentComponent = React.createClass({
getInitialState : function() {
return {
first: 1,
}
}
changeFirst: function(newValue) {
this.setState({
first: newValue,
});
}
render: function() {
return (
<a first={this.state.first} changeFirst={this.changeFirst.bind(this)} />
<b first={this.state.first} changeFirst={this.changeFirst.bind(this)} />
)
}
}
现在,在您的孩子组件 a
和 b
中,首先访问
变量使用 this.props.first
。当您希望首先更改的值时
调用 this.props.changeFirst()
ParentComponent的函数
。这将改变该值,因此将反映在两个孩子身上 a
和 b
。
Now in your child compoenents a
and b
, access first
variable using this.props.first
. When you wish to change the value of first
call this.props.changeFirst()
function of the ParentComponent
. This will change the value and will be thus reflected in both the children a
and b
.
我在这里编写组件 a
, b
将相似:
I am writing component a
here, b
will be similar:
var a = React.createClass({
render: function() {
var first = this.props.first; // access first anywhere using this.props.first in child
// render JSX
}
}
这篇关于如何从另一个组件访问一个组件的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!