有没有办法使用反应导航创建和分派/触发自定义事件?

Mon*_*ton 5 javascript events triggers dispatch react-native

借助 DOM,您可以轻松地使用 Javascript 创建触发自定义事件,如下所示:

var event = new Event('build');

// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);

// Dispatch the event.
elem.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)

有没有办法用 React-Native 做到这一点?

Mon*_*ton -2

对于我的情况,实际上有两种解决方案:

  1. https://reactnavigation.org/docs/en/function-after-focusing-screen.html
    使用react-navigation了解组件/屏幕何时获得焦点并使用“didFocus”事件侦听器触发操作:
import React, { Component } from 'react';
import { View } from 'react-native';
import { withNavigation } from 'react-navigation';

class TabScreen extends Component {
  componentDidMount() {
    const { navigation } = this.props;
    this.focusListener = navigation.addListener('didFocus', () => {
      // The screen is focused
      // Call any action
    });
  }

  componentWillUnmount() {
    // Remove the event listener
    this.focusListener.remove();
  }

  render() {
    return <View />;
  }
}

export default withNavigation(TabScreen);
Run Code Online (Sandbox Code Playgroud)
  1. https://redux.js.org/basics/example
    使用 Redux 作为应用程序的一个全局状态容器。

  • 我不明白您的答案与“自定义事件”问题有什么关系。 (2认同)