我正在尝试在 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> ) }