简体   繁体   English

通过使用道具从另一个组件 class 给出 state 值

[英]Giving a state value from another component class through using a prop

I am completely new in React Native and I am trying to improve my self with some making sample apps.我是 React Native 的新手,我正在尝试通过一些制作示例应用程序来提高自己。 For this scenario, I only want that when the Button is pressed, the state and the value of the toggle change, such as CLOSED and OPEN .对于这种情况,我只希望当按下Button时,state 和切换的值会发生变化,例如CLOSEDOPEN And Make Open is not changed.并且Make Open没有改变。 Now, I have three class components.现在,我有三个 class 组件。 I am not going to give App's class.我不会给出App的class。 I've alread completed it.我已经完成了。 In this class, I have added a prop:在这个 class 中,我添加了一个道具:

class A extends Component
{
    constructor(props)
    {
      super(props);
      this.state = {change: true};
    }
    render(){ 
     
     return(
      <View>
          <View ...
            <Text>CLOSED</Text>
          </View>
      </View>  
           
    );
  }
}

Here is my second class B:这是我的第二个 class B:

class B extends Component
{
  state = {isOpen : false};
  render()
  {
    onPress = () => {
       ...
    })
  }
    return(
       <View> 
         <View ...
            <A/>
            <Button 
               title="Make Open"
               onPress={this.onPress}
            />
          </View>
      </View>       
    );
  }
}

I am struggling with the prop.我正在与道具作斗争。 My question is that I want to pass the isOpen value from the class B 's state to class A by use of this prop.我的问题是我想通过使用此道具将class B的 state 的isOpen值传递给class A I think that I could not create state in class B .我认为我无法在class B中创建 state 。 What is the easiest way to solve this problem?解决这个问题的最简单方法是什么? If I gave not enough information, sorry for that.如果我没有提供足够的信息,很抱歉。

When you call component A from component B, you have to pass your state like so:当您从组件 B 调用组件 A 时,您必须像这样传递您的 state:

<A isOpen={this.state.isOpen} />

Then in component A, you can simply access it with props.isOpen .然后在组件 A 中,您可以简单地使用props.isOpen访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM