我正在尝试使用启用了fabric
的新架构
,在react-native
中集成Native UI
组件。
这是我的规范文件:
import type {HostComponent, ViewProps} from 'react-native';
import type {
DirectEventHandler,
BubblingEventHandler,
} from 'react-native/Libraries/Types/CodegenTypes';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
type Event = Readonly<{
text?: string;
}>;
interface NativeProps extends ViewProps {
text: string;
onClickHandler?: DirectEventHandler<Event>; ////Event name should start with on
}
export default codegenNativeComponent<NativeProps>(
'MyButtonView',
) as HostComponent<NativeProps>;
然后在本地端,我创建了以下文件
public class MyButtonViewManager extends SimpleViewManager<MyButtonView> {
public static final String NAME = "MyButtonView";
ReactApplicationContext mCallerContext;
public MyButtonViewManager(ReactApplicationContext reactContext) {
mCallerContext = reactContext;
}
@NonNull
@Override
public String getName() {
return NAME;
}
@NonNull
@Override
protected MyButtonView createViewInstance(@NonNull ThemedReactContext reactContext) {
return new MyButtonView(reactContext);
}
@ReactProp(name = "text")
public void setQrCodeText(MyButtonView view, String text) {
view.setText(text);
}
@Nullable
@Override
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
return MapBuilder.of("topOnClickHandler",
MapBuilder.of("registrationName", "onClickHandler")
);
}
}
public class MyButtonView extends androidx.appcompat.widget.AppCompatButton {
public MyButtonView(Context context) {
super(context);
configureViews();
}
private void configureViews(){
setBackgroundColor(Color.YELLOW);
setOnClickListener(view -> {
ReactContext reactContext = (ReactContext)getContext();
EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(
reactContext ,getId()
);
eventDispatcher.dispatchEvent(new MyButtonClickEvent(getId()));
});
}
}
public class MyButtonClickEvent extends Event<MyButtonClickEvent> {
public MyButtonClickEvent(int viewId) {
super(viewId);
}
@Override
public String getEventName() {
return "topOnClickHandler";
}
@Override
public void dispatch(RCTEventEmitter rctEventEmitter) {
super.dispatch(rctEventEmitter);
rctEventEmitter.receiveEvent(getViewTag(), getEventName(), Arguments.createMap());
}
@Nullable
@Override
protected WritableMap getEventData() {
WritableMap event = Arguments.createMap();
event.putString("message", "MyMessage");
return event;
}
}
dispatch
和RCTEventEmitter
都已被弃用,它们的替代方案是什么?我正研究RCTModernEventEmitter
,但它也继承了废弃的RCTEventEmitter
此外,在Native Android
端必须将事件名称从OnClickHandler
更改为topOnClickHandler
,否则会抛出hermes
错误。不确定为什么要加上top
前缀,为什么不能直接使用OnClickHandler
。