[英]react: reach the component's parent or transfer data from parent to child
Please tell me how you can in this scheme 请告诉我如何才能使用此方案
render()
{
return (
<Parent>
<Child1>
<Child2>
</Parent>
);
}
on the side of the components Parent
and Child
get the data that will be generated in the render ()
method or in the constructor (data access) 在组件
Parent
和Child
旁边,将获取将在render ()
方法或构造函数中生成的数据(数据访问)
It is clear that one of the ways is to transfer to props
, but if without it? 很明显,方法之一就是转移到
props
,但是如果没有的话?
For example, a state is set, in the Parent
constructor, this state of the parent is obtained and the same state is set, in the Child
constructor, the Parent
state is obtained and its state is set. 例如,设置一个状态,在
Parent
构造函数中,获取父级的该状态并设置相同的状态,在Child
构造函数中,获取Parent
状态并设置其状态。 As a result, some parameter is passed across the tree. 结果,某些参数跨树传递。
But in order to implement this, you need to somehow gain access to the parent of the component. 但是为了实现这一点,您需要以某种方式获得对组件父级的访问权限。
For example: 例如:
more beautiful option (and I do not know how to implement it - this option would be more preferable) 更漂亮的选项(而且我不知道如何实现它-此选项会更可取)
this.state = {
mydata: 123;
};
class Parent extends Component
{
constructor()
{
super();
this.state = {
mydata: this.getOwner().state.mydata; // = 123
};
}
}
class Child extends Component
{
constructor()
{
super();
this.state = {
mydata: this.getOwner().state.mydata; // = 123
};
}
}
less beautiful option (I know how to implement it) 不太漂亮的选择(我知道如何实现)
render()
{
return (
<Parent mydata = "123">
<Child1 mydata = "123">
<Child2 mydata = "123">
</Parent>
);
}
class Parent extends Component
{
constructor(props)
{
super();
this.state = {
mydata: props.mydata
};
}
}
class Child extends Component
{
constructor(props)
{
super();
this.state = {
mydata: props.mydata
};
}
}
you can achieve the wanted result by using something called Context as the following: 您可以使用以下称为Context的东西来达到所需的结果:
//outside of your class component
const MyContext = React.CreateContext();
//inside your class component
state = {mydata: "123"}
render()
{
return (
<MyContext value={this.state}>
<Parent>
<Child1>
<Child2>
</Parent>
</MyContext>
);
}
now inside any of the tree components: Parent
Child1
and Child2
you can reach the value of the shared state by saying this.context.mydata
现在内的任何树组件:
Parent
Child1
和Child2
你可以说达到共享状态的值this.context.mydata
learn more at https://reactjs.org/docs/context.html 进一步了解https://reactjs.org/docs/context.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.