在 React Native Android 上定义自定义原生事件 [英] Defining a custom native event on React Native Android
问题描述
我正在尝试在 Android 上的 React Native 应用程序中定义自定义事件.我有本机视图,它有一个本机按钮.当按钮被按下时,我想向我的 React Native 组件发送一条消息以显示一个模式屏幕.
I am trying to define a custom event in my React Native app on Android. I have native View, which has a native Button. When the button is pressed, I want to send a message to my React Native Component to show a modal screen.
我已经按照示例进行操作,但并不了解所有元素,并且在尝试中做了一些猜测.
I have followed the examples but don't understand all the elements, and have done a bit of guesswork in my attempt.
在我的 ViewManager 类中:
In my ViewManager class:
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 应用程序中显示模态视图.
So I would like, each time showModal
is called, for a JS event to be triggered to that I can show a modal view in the React Native app.
在我的 React 组件中,我有:
In my React Component I have:
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);
}
//...
}
我不明白的是映射是如何工作的,以及我如何定义事件(例如 示例).
What I don't understand is how the mapping works, and how I can define an event (like onChange in the example).
推荐答案
好吧,我没有展示我的 render
方法,这就是缺失的部分.我错过了在事件处理方法中传递的道具,在这种情况下 onPressModalButton={this_.showModal}
:
Well, I didn't show my render
method and that was where the missing part was. I missed out the prop that passes in the event handling method, in this case onPressModalButton={this_.showModal}
:
render() {
return (
<View style={styles.container}>
< MyNativeComponent style={{flex: 1}} onPressModalButton={this._showModal} />
</View>
)
}
这篇关于在 React Native Android 上定义自定义原生事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!