React Native:当警报出现在其上时,模态不会隐藏

vai*_*edy 10 alert react-native

我注意到一个奇怪的行为,如果Modal出现在其上,然后在它上面,如果出现警报,警报很快消失,用户不点击它上面的任何东西,即使以编程方式删除,Modal也不会从屏幕上删除.我认为是一个错误.有解决方法吗?

Slo*_*wyn 8

这似乎是React Native的一个麻烦.我也遇到过这个问题.修复它的最简单方法是在隐藏模态后调用带超时的警报: ... setTimeout(() => Alert.alert(msg), 10); ...


Spa*_*Bao 8

是的,我确实认为应该是反应本机的错误,我的代码通过react-native 0.33工作正常,升级到0.37后,然后遇到了同样的问题.

以下内容是我对react-native GitHub问题的评论:https://github.com/facebook/react-native/issues/10471#issuecomment-262450975,希望对您有所帮助:


我将react-native从0.33升级到0.37后遇到了类似的问题.我想在关闭Modal后显示一个Alert对话框,但是即使在我关闭Alert对话框并cmd + R用来重新加载应用程序之后,Modal也不会消失.仅在iOS中,它通过react-native 0.33正常工作.

代码喜欢以下内容:

renderModal() {
  return (
    <Modal
      animationType = 'fade'
      transparent={true}
      visible={this.state.isProcessing}
      onRequestClose={()=>{}}>
      <View style={styles.modalContainer}>
        <LoadingSpiner size='large' color='white' styleAttr='Normal'/>
      </View>
    </Modal>
  )
}

_pressNext() {
  // display a Modal with a spinner
  this.setState({isProcessing: true}}

  // network request
  // ...
}

componentWillReceiveProps(nextProps) {
    // ...

    // to hide the Modal with a spinner
    this.setState({isProcessing: false})
    Alert.alert('title', 'Something has done!', [
      { text: 'Got it', onPress: () => {} }
    ])
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试用来setTimeout解决它,代码喜欢以下:

componentWillReceiveProps(nextProps) {
    // ...

    // to hide the Modal with a spinner
    this.setState({isProcessing: false})
    setTimeout( () => {
      // this log will output
      console.log("show alert")
      // but Alert doesn't display
      // sometimes it will display occasionally
      Alert.alert("title", "msg")   
    }, 200)
}
Run Code Online (Sandbox Code Playgroud)

那么Modal会消失,但是,Alert对话框无法显示!

我也试过setTimeoutsetState回调中运行,像这样:

this.setState({isProcessing: false}, () => {
  setTimeout( () => {
    Alert.alert("title", "msg")
  }, 200)
}
Run Code Online (Sandbox Code Playgroud)

但是同样的结果,警报对话框还没有弹出.

最后,我决定在关闭"警报"对话框后隐藏Modal,这样可行!代码如下:

Alert.alert("title", "msg", [
  { text: "OK", onPress: () => { this.setState({ isProcessing: false } }    
])
Run Code Online (Sandbox Code Playgroud)