【问题标题】:How do I close a React Native Modal?如何关闭 React Native Modal?
【发布时间】:2019-06-26 11:38:17
【问题描述】:

我目前遇到了一个问题,我可以很好地打开我的 react-native 模式,但是一旦打开,我似乎无法关闭它。我大约三周前才开始使用 react-native,所以我对此非常陌生。

我已尝试实施我在网上找到的解决方案,但似乎没有什么对我有用。打开功能很棒,似乎工作得很好,但是当谈到关闭模态时,我尝试过的所有事情似乎都没有赋予模态这种能力。我无法在任何地方为我的确切问题找到可靠的解决方案!

这就是我打开模式的方式。

constructor(props) {
 super(props);
  this.state = {
   refreshing: false,
    display: false
  };
}

triggerModal() {
 this.setState(prevState => {
  return {
    display: true
   }
  });
}

<View>
  <Button onPress = { () => this.triggerModal() } title = "Open Modal"></Button>

  <DisplayModal display = { this.state.display } />
</View>

这是模态本身,我正在尝试使用一个按钮来关闭它。

import React from 'react'
import { Modal, View, Image, Text, StyleSheet, Button } from 'react-native';

const DisplayModal = (props) => (
  <Modal visible={ props.display } animationType = "slide" 
onRequestClose={ this.display }>
<View>
  <Button title="close" onPress = { () => !props.display }></Button>
</View>
</Modal>
)

export default DisplayModal;

由于我对 react-native 的了解有限,我很难理解框架的某些方面是如何运作的……我可能只是在代码的某个地方犯了一个愚蠢的错误。

感谢您对这个问题的任何帮助!

【问题讨论】:

    标签: javascript react-native expo


    【解决方案1】:

    您几乎已经完成了,但是我们可以进行一些调整以使其按您的意愿工作。

    由于您的DisplayModal 没有自己的状态,因此该状态必须由其父组件控制。因此,考虑到这一点,我们可以执行以下操作。首先将一个名为closeDisplay 的附加属性传递给DisplayModal。我们将传递一个将state 中的display 属性设置为false 的函数。

    <DisplayModal 
      display={this.state.display} 
      closeDisplay={() => this.setState({display: false})} // <- we are passing this function
    />
    

    然后在我们的DisplayModal 组件中,我们将调用该函数来关闭模式。所以你的DisplayModal 组件应该是这样的:

    const DisplayModal = (props) => (
      <Modal 
        visible={ props.display } 
        animationType = "slide" 
        onRequestClose={ this.display }>
        <View>
          <Button 
           title="close" 
           onPress = { () => props.closeDisplay() }> // <- here we call the function that we passed
        </Button>
        </View>
      </Modal>
    )
    

    注意DisplayModal组件中ButtononPress函数,我们调用的是函数closeDisplay()。然后,此函数设置父组件中的状态,然后将其传递回DisplayModal 组件,使其隐藏。

    【讨论】:

    • 效果很好!非常感谢您花时间逐步解释解决方案。绝对让我更好地了解事情应该如何运作。我很感激安德鲁!
    • 不客气,我们都从某个地方开始。我发现单行答案很糟糕,因为它对那些寻求帮助的人没有任何帮助。一点解释就大有帮助。但让它变得更好的是你花时间写了一个好问题。你展示了你做了什么,并且清楚你想要完成什么。继续努力,坚持不懈,您将到达那里:)
    • 我完全同意你的看法。当有人写了一个快速示例来说明他们如何工作而没有完全解释示例的各个方面如何工作时,我无法忍受......再次感谢!非常感谢帮助和客气话。我一定会继续努力,因为到目前为止我很享受!
    猜你喜欢
    • 2020-11-16
    • 2021-02-08
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2018-03-28
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多