关闭 React native Modal 不起作用

Closing React native Modal is not working

我想在 React native 中有一个模态框,如下所示,模态框应该关闭 onPress 到 'close' 文本。 demo picture here

ModalProps 来自前一个组件为真。 OnPress to 'close' 我希望 'visible' 为 false 并关闭 Modal。我的 OS 是 Android。代码如下:

type ModalProps = {
    visible: boolean  // visible = true here from the previous screen
}


const closeModal = ():void => {
    // code to make the visible false
}

function myModal ({visible}: ModalProps) {
    return (
        <Modal visible={visible}>
            <View>
                <Text> this is my Modal</Text> 
            </View>
            <View>
                <Text onPress={() => this.closeModal()}>Dismiss</Text>
            </View>
        </Modal>
    );
}

export default myModal;

我该怎么做?

你的父组件应该有一个类似 modalVisible 的状态来处理模态可见性。 所以你的父组件应该像 onPressClose

这样传递函数属性

父组件:

import React, {useState} from 'react';
import { View, Text } from 'react-native';
import Modal from 'react-native-modal';

function ParentComponent() {

  const [visible, setVisible] = useState(true); // Starts with what visibility you want.

  return (
    <MyModal visible={visible} onPressClose={() => setVisible(false)} />
   );
}

模态组件:

// imports...

function MyModal ({visible, onPressClose}){
  return (
    <Modal visible={visible}>
      <View>
         <Text> this is my Modal</Text> 
      </View>
      <View>
        <Text onPress={onPressClose}> Dismiss </Text>
      </View>
    </Modal>

   );
  }