第一部分,在ReactNative中,原生与js交互常用的是原生通过向js发送事件,参考webview源代码。
1、定义事件与发送消息方法
public class ReactExpandListViewEvent extends Event<ReactExpandListViewEvent> {
public static final String EVENT_NAME = "topExpandListViewClick";
private WritableMap mEventData;
public ReactExpandListViewEvent(int viewId, WritableMap eventData) {
super(viewId);
mEventData = eventData;
}
@Override
public String getEventName() {
return EVENT_NAME;
}
@Override
public void dispatch(RCTEventEmitter rctEventEmitter) {
rctEventEmitter.receiveEvent(getViewTag(), getEventName(), mEventData);
}
}
2、注册事件(topExpandListViewClick)
在ViewManager重写以下方法
//注册事件(ReactExpandListViewEvent)
@Override
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
return MapBuilder.<String, Object>builder()
.put("topExpandListViewClick", MapBuilder.of("registrationName", "onExpandListViewClick"))
.build();
}
3、组装发送到js的数据
在ViewManger中组装数据
//组装发送到js的数据
private WritableMap createExpandListViewEvent(ExpandableListView expandListView) {
WritableMap event = Arguments.createMap();
event.putDouble("target", 2222222);
event.putString("url", "22222");
event.putBoolean("loading", true);