是否可以使用React-Native创建和分发/触发自定义事件?

问题描述 投票:2回答:1

使用DOM,您可以像这样轻松地使用Javascript创建触发器自定义事件:

var event = new Event('build');

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

// Dispatch the event.
elem.dispatchEvent(event);

是否有使用React-Native做到这一点的方法?我知道NativeEventEmitter的存在,这是RN与Java平台与本机通信的方式。

javascript react-native events triggers dispatch
1个回答
0
投票

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

  1. https://reactnavigation.org/docs/en/function-after-focusing-screen.html使用反应导航了解何时接收到组件/屏幕使用“ 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);
  1. https://redux.js.org/basics/example将Redux用作应用程序的一个全局状态容器。
© www.soinside.com 2019 - 2024. All rights reserved.