【问题标题】:react: reach the component's parent or transfer data from parent to childreact:到达组件的父级或将数据从父级传输到子级
【发布时间】:2019-04-15 19:49:57
【问题描述】:

请告诉我你怎么能在这个方案中

render()
{
    return (
<Parent>
    <Child1>
    <Child2>
</Parent>
    );
}

在组件Parent和Child一侧获取将在render ()方法或构造函数中生成的数据(数据访问)

明明一种方式是转props,但是如果没有呢?

例如,设置了一个状态,在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
        };
    }
}

【问题讨论】:

    标签: javascript reactjs class react-native inheritance


    【解决方案1】:

    您可以通过使用名为 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>
                );
            } 
    

    现在在任何树组件中:Parent Child1 和 Child2 您可以通过说 this.context.mydata 来达到共享状态的值

    通过https://reactjs.org/docs/context.html了解更多信息

    【讨论】:

      猜你喜欢
      • 2017-07-20
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多