ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

在React Native Android上定义自定义本机事件

2019-07-06 03:23:36  阅读:192  来源: 互联网

标签:android react-native


我正在尝试在Android上的React Native应用程序中定义自定义事件.我有本机View,它有一个原生Button.按下按钮时,我想向我的React Native Component发送一条消息,以显示模态屏幕.

我已经按照这些例子但不了解所有元素,并且在我的尝试中做了一些猜测.

在我的ViewManager类中:

public class MyViewManager extends SimpleViewManager<MyView> {

    // Contructor etc...

    @Override
    protected MyView createViewInstance(ThemedReactContext themedReactContext) {
        //... Create and return the view 
    }

    /**
     * Custom native events
     * @return Map of additional events
     */
    @Override
    public @Nullable
    Map getExportedCustomDirectEventTypeConstants() {
        return MapBuilder.of(
                "showModal",
                MapBuilder.of("registrationName", "onPressModalButton")
        );
    }
}

自定义视图:

public class MyView extends View {

    public MyView(Context c)
    {
        super(c);
    }

    public void showModal() {
        Log.d("MyView", "showModal");

        WritableMap event = Arguments.createMap();
        event.putString("showModal", "onPressModalButton");
        ReactContext reactContext = (ReactContext)getContext();
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                getId(),
                "showModal", 
                event);
    }
}

所以我想,每次调用showModal时,要触发一个JS事件,我可以在React Native应用程序中显示模态视图.

在我的React组件中,我有:

  class MyNativeComponent extends React.Component {
    static propTypes = {
      ...View.propTypes,
      onPressModalButton: React.PropTypes.func
    }
    render() {
      return <MyView {...this.props} />
    }
  }

  const MyView = requireNativeComponent('MyView', MyNativeComponent, { nativeOnly: {showModal: true} })

  class MyComponent extends React.Component {
    constructor(props) {
      super(props);
      this._showModal = this._showModal.bind(this);
    }

    _showModal(event: Event) {

      console.log("showModal from React!")
        if (!this.props.onPressModalButton) {
          return;
        }
      this.props.onPressModalButton(event.nativeEvent.showModal);
    }

    //...
  }

我不明白的是映射是如何工作的,以及如何定义事件(如example中的onChange).

解决方法:

好吧,我没有展示我的渲染方法,那就是缺失的部分.我错过了传递事件处理方法的道具,在本例中是onPressModalButton = {this_.showModal}:

render() {
  return (
    <View style={styles.container}>
      < MyNativeComponent style={{flex: 1}} onPressModalButton={this._showModal} />
    </View>
  )
}

标签:android,react-native
来源: https://codeday.me/bug/20190706/1393727.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有