简体   繁体   English

为什么 props 不能与我的子组件 React JS (react native) 一起使用

[英]Why props is not working with my child component React JS (react native)

So this is in my main class where I am trying to render a modal from a child component.所以这是在我的主要 class 中,我试图从子组件呈现模式。

        <NewModal  
            transparent={true}
            show={props.show}
            >
        </NewModal>

show is initially set as false in the parent constructor and after one of my elements in my flatList is pressed I set show to true However I am not sure why it is not working so well, here is my child class, I have tried lots of varients with the props and nothing seems to be working, the best I can get is the modal showing before I even press on one of my elements in the flat list. show 最初在父构造函数中设置为 false 并且在我的 flatList 中的一个元素被按下后我将show 设置为 true但是我不确定为什么它不能很好地工作,这是我的孩子 class,我尝试了很多道具的变体,似乎没有任何效果,我能得到的最好的结果是在我按下平面列表中的一个元素之前的模态显示。

Child component:子组件:

 const NewModal = (props) => {
   return (
      <Modal transparent={true} visible={props.show}  >
        <View style={styles.modalView}>
          <View>
           <Text>Modal Text</Text>
          </View>
         <Button title="Back" onPress={() => visible=false } />
       </View>
    </Modal>
  );

}; };

 const styles = StyleSheet.create({
 modalView: {
  marginTop: 100,
  height: "70%",
  width: "95%",
  alignSelf: "center",
  borderRadius: 5,
  borderWidth: 0.1,
  shadowOpacity: 0.7,
  backgroundColor: "white",
 },
 });

  export default NewModal; 

If you show state is managed in the parent component, you have to manage it's updation in the parent component too.如果您显示 state 是在父组件中管理的,那么您也必须在父组件中管理它的更新。 To change it's value when user click the Back Button component, you have write a function in the parent component and pass that function as a prop to the child.要在用户单击后退按钮组件时更改其值,您必须在父组件中编写 function 并将 function 作为道具传递给子组件。 Then child would then invoke that function to update the state.然后孩子会调用 function 来更新 state。

Parent:家长:

  <NewModal  
     transparent={true}
     show={state.show}
     toggleShow={ () => this.setState({ show:false }) }
   >
     ....
   </NewModal>

Child:孩子:

<Button title="Back" onPress={() => this.props.toggleShow() } />

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

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