Closing modal in child component React Native

2019-08-27 18:54发布

I have two components in react native and I'm unable to close a modal from my child component.

ListTrips - Parent

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}
>

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

2条回答
贪生不怕死
2楼-- · 2019-08-27 19:18

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 :)

查看更多
smile是对你的礼貌
3楼-- · 2019-08-27 19:32

ModalAddTrip.js

  _toggleModal = () =>
      this.setState({ isVisible: !this.state.isVisible });
  ....

  render() { 
  ....
   <Modal
    isVisible={isVisible}
    onBackdropPress={onBackDropPress}
  >
      <Button
            style={{ fontSize: 18, color: 'white' }}
            containerStyle={{
              padding: 8,
              marginLeft: 70,
            }}
            onPress={this._toggleModal} >
</Modal>
查看更多
登录 后发表回答