请告诉我如何参与此计划
render()
{
return (
<Parent>
<Child1>
<Child2>
</Parent>
);
}
组件侧的Parent
和Child
获取将在render()
方法或构造函数中生成的数据(数据访问)
很明显,其中一种方式就是转入props
,但是如果没有呢?
比如设置一个状态,在Parent
构造函数中,获取parent的这个状态并设置同样的状态,在Child
构造函数中,获取Parent
状态并设置其状态。结果,一些参数通过树传递。
但是为了实现这一点,您需要以某种方式获得对组件父组件的访问权限。
例如:
更漂亮的选项(我不知道如何实现它 - 这个选项会更可取)
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
};
}
}
不太漂亮的选项(我知道如何实现它)
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
};
}
}
最佳答案
您可以通过使用名为上下文的内容来实现所需的结果,如下所示:
//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>
);
}
现在在任何树组件中:Parent
Child1
和 Child2
您可以通过输入 来获取共享状态的值this.context.mydata
关于javascript - react : reach the component's parent or transfer data from parent to child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55696320/