首页 > 解决方案 > 在子组件 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 的一个函数中,但这也不起作用。

任何帮助是极大的赞赏。谢谢

标签: react-nativemodal-dialogrefreact-props

解决方案


这是我用来处理模态的解决方案。

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();
    }
  }

让我知道你是否能正常工作:)


推荐阅读