简体   繁体   中英

How to pass state from custom component to parent in React Native

I'm trying to create a custom Modal component to be reused throughout my app but I'm struggling to manage the state. An example usage of this modal is to have a button that makes it visible. To me, that would seem to suggest the state of the modal needs to be stored in the parent component, otherwise there's no way to access the initially false visibility to make it true. However, I'm unsure of how to access the state in the parent component from the child modal. And maybe that's wrong altogether. Seems like storing state in the custom component would be cleaner.

My many attempts have all been somewhere along the lines of the below. Please understand I am omitting a significant amount of what I feel is irrelevant code here. I'm not looking for code troubleshooting, I'm struggling with the concept as a whole.

import React, { useState } from 'react';
import { << various components >>, Modal } from 'react-native';
import CustomModal from << path >>;

export default function App() {
  const [modalVisible, setModalVisible] = useState(false);

  return (
    << screen components >>
    <CustomModal
      visible={modalVisible}
      << etc. >>
    />

    <TouchableOpacity onPress={setModalVisible(true)}>
      <Text>Open Modal</Text>
    </TouchableOpacity>
  );
}

<< styles, etc. >>

So this succeeds in making the modal visible, but I'm not sure how to close it. There's a button on the modal intended to close it, but I can't figure out what the onPress should do. I want to access the modalVisible state in the parent to call setModalVisible(false), but I can't fathom how to do it.

Am I thinking about this all wrong? I've seen several examples that use 'this' and 'constructor' and 'super' etc. which are things I thought were replaced by hooks and they just confuse me (please go easy on me). I'm also sure you can do it with Redux, but I'm trying to better understand "lifting up state" if I'm even saying it right.

Thanks for your help.

Pass as prop for setModalVisible in your CustomModal component like:

    <CustomModal
      visible = {modalVisible}
      setModal = {setModalVisible(!modalVisible)}
      << etc. >>
    />

Then on the closing of your modal call setModal .

Hope this works for you.

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