有没有一种方法可以使用React-Native创建和分发/触发自定义事件? [英] Is there a way to create and dispatch/trigger custom event with React-Native?

查看:63
本文介绍了有没有一种方法可以使用React-Native创建和分发/触发自定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With DOM, you can easily create a trigger custom event with Javascript like so:

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平台与本机通信的方式.

Is there a way to do that with React-Native? I know the existent of NativeEventEmitter which is way for RN to communication with native the Platform in Javascript.

推荐答案

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

There are actually two solutions for my case:

  1. https://reactnavigation.org/docs/zh-CN/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);

  1. https://redux.js.org/basics/example
    将Redux用作应用程序的一个全局状态容器.

这篇关于有没有一种方法可以使用React-Native创建和分发/触发自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆