簡體   English   中英

有沒有辦法用 React-Native 創建和發送/觸發自定義事件?

[英]Is there a way to create and dispatch/trigger custom event with 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);

有沒有辦法用 React-Native 做到這一點? 我知道 NativeEventEmitter 的存在,這是 RN 在 Javascript 中與原生平台通信的方式。

我的情況實際上有兩種解決方案:

  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);
  1. https://redux.js.org/basics/example
    使用 Redux 作為應用程序的一個全局狀態容器。

React Native 提供了NativeEventEmitter來處理自定義事件。

import { NativeEventEmitter } from 'react-native';
const eventEmitter = new NativeEventEmitter();

eventEmitter.emit('custom-event', { data: 'test' });

eventEmitter.addListener('custom-event', event => {
  console.log(event); // { data: 'test' }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM