子组件React Native中的关闭模式 [英] Closing modal in child component React Native
问题描述
我在本机反应中有两个组件,无法从子组件中关闭模态.
I have two components in react native and I'm unable to close a modal from my child component.
ListTrips-父级
ListTrips - Parent
ModalAddTrip-子项
ModalAddTrip - Child
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中的函数中,但这也不起作用.
I'm unable to close the modal once I open it. I know its something to do with referencing/props but I've messed around with it for hours and I cannot get anywhere. I was trying something along the lines of this.props.closeModal;
along with switching the ref to the child component but it didn't work either. inside a function in ModalAddTrip but that wouldn't work either.
任何帮助将不胜感激. 谢谢
Any help is greatly appreciated. Thanks
推荐答案
这是我用来处理模式的解决方案.
Here is a solution which I use to handle modal.
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>
);
}
}
如果我向后按,该模式将关闭->它可以自行关闭.
If I press behind it, the modal will close -> it can close itself.
现在可以从父组件中进行管理,只需从模态中获取引用即可:
Now to manage it from the parent component just get a ref from your modal :
<MyModal
ref={ref => {
this.myModal = ref;
}}
/>
您可以从父组件中切换它:
And you can toggle it from the parent component :
toggleMyModal = () => {
if(this.myModal){
this.myModal.toggleModal();
}
}
让我知道您是否可以使用它:)
Let me know if you got it working :)
这篇关于子组件React Native中的关闭模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!