簡體   English   中英

react native新架構的fabric組件如何為android和iOS做事件處理?

[英]How to do event handling for android and iOS in react native's new architecture for fabric components?

我正在嘗試創建一個Fabric組件。 我已經讓它大部分工作了。 我面臨的唯一問題是我無法讓點擊偵聽器為fabric組件工作。

我創建了一個規范文件

import type {HostComponent, ViewProps} from 'react-native';
import type {DirectEventHandler} from 'react-native/Libraries/Types/CodegenTypes';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

type Event = Readonly<{
  value: string;
}>;

interface NativeProps extends ViewProps {
  text: string;
   onClickHandler?: BubblingEventHandler<Event>; ////Event name should start with on
}

export default codegenNativeComponent<NativeProps>(
  'MyButtonView',
) as HostComponent<NativeProps>;

對於android ,我的fabric組件如下所示

public class MyButtonView extends androidx.appcompat.widget.AppCompatButton {

    public MyButtonView(Context context) {
        super(context);
        configureViews();
    }

    private void configureViews(){
        setBackgroundColor(Color.YELLOW);
        setOnClickListener(view -> {
            onReceiveNativeEvent();
        });
    }

    public void onReceiveNativeEvent() {
        WritableMap event = Arguments.createMap();
        event.putString("message", "MyMessage");
        ReactContext reactContext = (ReactContext)getContext();
        reactContext.getJSModule(RCTModernEventEmitter.class)
                .receiveEvent(getId(),getId(),"onClickHandler",true,0,event,1);

    }
}

不確定在 receiveEvent 中將first param as intcanCoalesceEventcustomCoalesceKeycategory receiveEvent

ViewManager我也添加了以下代碼

@Nullable
@Override
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
    Log.i("here55","999999");
    return MapBuilder.of("onClickHandler",
            MapBuilder.of("registrationName", "onClickHandler")
    );
}

對於android ,我沒有得到從native androidjs端的callback

我正在關注https://reactnative.dev/docs/native-components-android但它適用於舊架構,我認為不適用於fabric組件

同樣適用於iOS https://reactnative.dev/docs/native-components-ios ,該文檔對新架構不是很有幫助

對於iOS ,我創建了headerobjective-c++文件

通常,如果我們想添加屬性,我們會這樣做

RCT_EXPORT_VIEW_PROPERTY(text, NSString)

不確定如何為事件處理程序執行此操作

完整的源代碼在這里https://github.com/PritishSawant/ReactNativeFabricEventListenerExample

iOS

假設您發布的本機規范是正確的(我不太熟悉 TypeScript + Codegen duo),當您在ios/目錄中運行pod install命令時, codegen應該在React-Codegen pod 中生成EventEmitters cpp 文件(+ 標頭)(您可以看到下面如何在 XCode 中找到它)

鏈接到帶有 Pod 結構的屏幕截圖

然后,您可以在Objective-C++代碼中使用這些類來發出事件:

if (_eventEmitter != nullptr) {
    std::dynamic_pointer_cast<const facebook::react::$$NAME OF YOUR EVENT EMITTER TYPE$$>(_eventEmitter)
        ->onEvent(facebook::react::$$NAME OF YOUR EVENT EMITTER TYPE::OnEvent{.value = $$VALUE$$});
}

請參閱下面的鏈接以了解它是如何在react-native-screens中完成的

  1. Flow中的原生組件規范
  2. Obj-C++ 代碼中的事件發射
  3. 屏幕管理器中的事件曝光- 我不太確定這條線是否必要,還沒有測試過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM