简体   繁体   中英

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.

        <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.

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. 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. Then child would then invoke that function to update the state.

Parent:

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

Child:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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