首页 > 解决方案 > React Native:当您滑回已安装的屏幕时如何触发事件?

问题描述

在我的 React Native 应用程序中,我有一个想要在某个屏幕出现时触发的事件。我将事件放入componentDidMount,因此它会在屏幕首次加载时触发,但如果我离开屏幕并且向左滑动以返回屏幕,则屏幕已经安装,因此不会触发事件。

我应该如何处理这个?

标签: javascriptreactjsreact-native

解决方案


如果您正在使用react-navigation,您可以执行此操作componentDidMount以在已安装的屏幕上触发事件。

componentDidMount() {
    const {navigation} = this.props;
    this.onFocusTrigger = navigation.addListener('focus', () => {
      // trigger your event
    });
  }

除此之外'focus',您还可以根据需要使用以下内容。

  • willFocus
  • didFocus
  • didBlur
  • willBlur

您需要像这样在 componentWillUnmount 中取消订阅侦听器

componentWillUnmount() {
    this.onFocusTrigger();
  }

推荐阅读