【问题标题】:Modal is not closing in my react-native app?Modal 没有在我的 react-native 应用程序中关闭?
【发布时间】:2019-06-03 07:21:49
【问题描述】:

我正在创建一个在不同屏幕中使用 Modal 的应用程序。我为所有 Modal 创建了一个通用组件。我在其中传递 jsx 并根据全局变量使其可见。但是当我打开一个模态然后关闭它并移动到下一个屏幕然后在下一个屏幕中打开另一个模态时问题就来了,前一个屏幕的模态也在后台。

我试图根据两个变量(如全局变量和另一个局部变量)使其可见,但模态仍然没有关闭。

这是我常用的模态组件

  render() {
    let { GlobalStore, renderContent = () => {}, modalStyle, modalHeight = '50%' } = this.props;
    return (
      <Modal
        isVisible={GlobalStore.showModal}
        backdropColor={Constants.COLORS.BLACK}
        backdropOpacity={0.4}
        onBackdropPress={() => GlobalStore.toggleModal(false)}
        style={[styles.bottomModal,modalStyle]}>
        <View style={[styles.modalContent,{height: modalHeight}]}>
          {renderContent}
        </View>
      </Modal>
    )
  }
}

并在诸如

之类的屏幕上使用它
   {this.openModal?
    <CustomModal visible={GlobalStore.showModal&&this.openModal} 
      modalHeight = {this.modalHeight} renderContent = 
      {this.ModalContent()}/>
       :
     null
    }

我只想关闭之前在后台出现的模式。我不想为所有模式创建不同的文件。任何形式的帮助将不胜感激。谢谢。

【问题讨论】:

    标签: javascript react-native jsx mobx-react


    【解决方案1】:

    将 GlobalStore.showModal 设为字符串而不是布尔值。

        //action
        const showModal = (modalType = "GLOBAL") => ({type: "SHOW_MODAL", modalType})
    
    
        //common modal
        //dispatch action
        dispatch(showModal());
        //check for the visibbility with the global string
        <Modal
            isVisible={GlobalStore.showModal === "GLOBAL"}
            {...restProps}
        />
    
    
        //custom modal
        //dispatch action with custom string
        dispatch(showModal("CUSTOM_MODAL"));
        //check for the visibilty with that custom string
        <CustomModal
            isVisible={GlobalStore.showModal === "CUSTOM_MODAL"}
            {...restProps}
        />
    
        //hide all the modals
        dispatch(showModal(""))
    

    【讨论】:

    • 为什么?我的意思是两者有什么区别,bool有什么问题?
    • 您可以检查匹配的字符串而不是 bool(这将只允许匹配的字符串可见)。在上面的示例中,action 调度 string(CUSTOM_MODAL 为您自定义模式和 GLOBAL 为您常见) 而不是 bool。你可以在你的模式中检查这个字符串(不管它是什么)。
    【解决方案2】:

    模型是覆盖特殊组件,但是它们应该由其父组件控制。我认为您没有卸载前一个屏幕,并且因为您使用的是单个全局变量,所以所有未安装的模式都具有 true 值。我会将可见性变量移动到状态组件并限制范围,或者您可以将建议与字符串一起使用,但命名各种模态,以便全局变量仅指向一个模态。

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      相关资源
      最近更新 更多