2016-10-05 44 views
3

我想在Android上的React Native應用程序中定義自定義事件。我有原生視圖,它有一個本地按鈕。按下按鈕時,我想向我的React Native Component發送消息以顯示模態屏幕。在React Native上定義自定義本機事件Android

我遵循了這些例子,但不明白所有的元素,並且在我的嘗試中做了一些猜測。

在我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應用程序中的模式視圖。

在我的陣營組件我有:

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)定義的事件。

+1

感謝這篇文章指出我在正確的方向。 [我試圖在一篇相關文章上綜合解決方案。](https://stackoverflow.com/a/44207488/383414) –

回答

1

嗯,我沒有顯示我的render方法,那是缺少的部分。我錯過了通過事件處理方法傳遞的道具,在這種情況下,onPressModalButton={this_.showModal}

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