react-native - 在子组件 React Native 中关闭模式
问题描述
我在本机反应中有两个组件,我无法从我的子组件中关闭模式。
ListTrips - 父级
ModalAddTrip - 孩子
ListTrips.js
import ModalAddTrip from './ModalAddTrip';
....
....
this.state = {
isModalAddTripVisible: false
}
....
handleDismissModalAddTrip = () => {
this.setState({ isModalAddTripVisible: false });
};
closeModal() {
this.refs.ModalAdd.handleDismissModalAddTrip();
}
....
<ModalAddTrip
ref="ModalAdd"
isVisible={this.state.isModalAddTripVisible}
onBackDropPress={this.handleDismissModalAddTrip}
closeModal={() => this.closeModal()}
onRequestClose={this.handleDismissModalAddTrip}
/>
ModalAddTrip.js
<Modal
isVisible={isVisible}
onBackdropPress={onBackDropPress}
closeModal={this.props.child}
>
<Button
style={{ fontSize: 18, color: 'white' }}
containerStyle={{
padding: 8,
marginLeft: 70,
}}
onPress={this.closeModal}
>
一旦我打开它,我就无法关闭它。我知道它与引用/道具有关,但我已经搞砸了好几个小时,但我无处可去。我正在尝试this.props.closeModal;
将 ref 切换到子组件的方式,但它也不起作用。在 ModalAddTrip 的一个函数中,但这也不起作用。
任何帮助是极大的赞赏。谢谢
解决方案
这是我用来处理模态的解决方案。
export default class MyModal extends React.Component<Props, State>{
constructor(props: Props){
super(props);
this.state = {
visible: false,
}
}
// Use this method to toggle the modal !
toggleModal = () => {
this.setState({visible: !this.state.visible});
}
render(){
return(
<Modal
isVisible={this.state.visible}
hideModalContentWhileAnimating
onBackdropPress={() => {
this.toggleModal();
}}
useNativeDriver
>
<View style={{backgroundColor: "white", padding: 5}}>
</View>
</Modal>
);
}
}
如果我按下它,模态将关闭->它可以自行关闭。
现在要从父组件管理它,只需从您的 modal 获取一个 ref :
<MyModal
ref={ref => {
this.myModal = ref;
}}
/>
您可以从父组件切换它:
toggleMyModal = () => {
if(this.myModal){
this.myModal.toggleModal();
}
}
让我知道你是否能正常工作:)
推荐阅读
- angular - 带有表单控件的材料日期选择器遮罩
- mysql - 一个应用程序在heroku中有两个数据库
- scala - 为 Apache Spark 示例运行 Cypher (CAPS)
- ios - 检查 iOS 中后台的 Wi-Fi 网络变化,如 blynkmyplant iOS 应用程序
- c# - 如何使用 Moq 模拟 IMongoCollection.Find
- linux - Linux中多核处理器从实模式到保护模式的转换
- android - 是否可以在 Delphi for Android 中使用 TelecomManager?
- excel - Spark 连接到网络文件夹
- python - python中与grep -B等效的代码是什么?
- macos - 笔记软件推荐