简体   繁体   中英

React native modal open modal from different component using visible prop

How could i open Modal from different component file using my visible prop that is passed inside isVisible with some state and button. Right now the modal is not opening. I am using react-native-modal ( https://github.com/react-native-modal/react-native-modal )

 type ModalProps = {
        visible: boolean;
    };

export function Modal({ visible }: ModalProps) {
    return (
        <ReactNativeModal isVisible={visible} >
                <Pressable>
                    <Icon size={14} name="icon1" />
                </Pressable>
        </ReactNativeModal>
    );
}

Calling component in different file

 const [isModalVisible, setModalVisible] = React.useState(false);

    function handleModalClose() {
        setModalVisible(false);
    }

    function handleModalOpen() {
        setModalVisible(true);
    }

<Button title="Modal one" onPress={handleModalOpen}>
 <Modal visible={isModalVisible}></Modal>
</Button>

You should pass isModalVisible as visible prop to the Modal component:

<Modal visible={isModalVisible}></Modal>

If you need to close the modal from the Modal component, you can pass also the setModalVisible function:

type ModalProps = {
    visible: boolean;
    setModalVisible: React.Dispatch<React.SetStateAction<boolean>>;
};

export function Modal({ visible, setModalVisible }: ModalProps) {
    const handleClose = () => {
        setModalVisible(false);
    }

    ...

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