我目前在 React Native 项目中遇到与 Modal 组件相关的问题。尽管设置了一个按钮来关闭模式,但它并没有按预期工作。这是我的代码的简化版本:
import React, { useState } from 'react';
import { View, Text, Modal, Button } from 'react-native';
export default function MyComponent() {
const [isModalVisible, setModalVisible] = useState(false);
const handleOpenModal = () => {
setModalVisible(true);
};
const handleCloseModal = () => {
setModalVisible(false);
console.log('Modal closed!');
};
return (
<View>
<Button title="Open Modal" onPress={handleOpenModal} />
<Modal visible={isModalVisible} animationType="slide">
<View>
<Text>Modal Content</Text>
<Button title="Close Modal" onPress={handleCloseModal} />
</View>
</Modal>
</View>
);
}
尽管有handleCloseModal 函数,按下“关闭模态”按钮并不会按预期关闭模态。函数内部的日志语句也不会出现在控制台中。
有人可以提供指导,指导如何排查和解决 React Native 中按下按钮时 Modal 未关闭的新问题吗?任何见解或建议将不胜感激。谢谢!
试试这个:
import React, { useState } from 'react';
import { View, Text, Modal, Button } from 'react-native';
export default function MyComponent() {
const [isModalVisible, setModalVisible] = useState(false);
const handleOpenModal = () => {
setModalVisible(true);
};
const handleCloseModal = () => {
setModalVisible(false);
console.log('Modal closed!');
};
return (
<View>
<Button title="Open Modal" onPress={handleOpenModal} />
{isModalVisible && <Modal visible={isModalVisible} animationType="slide">
<View>
<Text>Modal Content</Text>
<Button title="Close Modal" onPress={handleCloseModal} />
</View>
</Modal>
}
</View>
);
}