javascript - 如何将 React Native 自定义警报作为函数调用?

标签 javascript react-native alert

我正在开发一个 React Native 应用程序。我使用 modal 创建了自己的自定义 alert 作为 component。当我使用它时,我总是需要在我的 render() 函数中添加我的 alert 组件。

有没有什么方法可以使用自定义警报而不用在我的 render() 函数中渲染它?

我的意思是,我可以在 react-native 中使用 Alert,方法是将其称为 Alert.alert()。我也想像那样使用我自己的自定义警报。

我该怎么做?

最佳答案

你可以这样做

class SomeComponent extends Component {
  static myComponentInstance

  constructor(props) {
    super(props)

    this.state = {
      visible: false,
      text: ""
    }

    SomeComponent.myComponentInstance = this
  }

  static show(text) {
    SomeComponent.myComponentInstance._show(text)
  }


  _show(text) {
    this.setState({ visible: true, text })
  }

  render(){

    <Modal visible={this.state.visible}>
       <Text>{this.state.text}</Text>
    </Modal>
  }
}

const AppRoot = () => (
  <View>
    <Navigator />
    <SomeComponent/>
  </View>
)

为了展示它,你可以在任何地方做 SomeComponent.show("some text")

关于javascript - 如何将 React Native 自定义警报作为函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56424312/

相关文章:

javascript - 如何在 Typescript 中使用 SolidJS 的 <Show> 标签

javascript - dc.js 重新选择已渲染的图表

javascript - 在 PHP 中向 AJAX 发送大量参数

react-native - react native 操作栏和 react native 菜单

datatable - 如何在 native react 中同步两个 ScrollView ?

javascript - 如何在 alert() 框中输入内容?

ios - Cordova InAppBrowser 事件监听器未显示 alert() - 与 Cordova window.alert Hook 冲突

取消中的javascript警告框

带有 console.log 的 JavaScript 进度条

javascript - Android的String.includes()和String.startsWith()的区别