问题描述
我想在 React Native 中有一个像下面这样的 Modal,其中 Modal 应该关闭 onPress 到“关闭”文本。 demo picture here
ModalProps 来自前一个组件为真。 OnPress 以“关闭”我希望“可见”为假,并关闭模态。我的操作系统是安卓。代码如下:
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>
);
}