如何在Android中实现React Native UI组件方法 [英] How to implement a React Native UI component method in Android
问题描述
对我来说很明显,对于react-native本机模块,我们可以使用@ReactMethod
导出方法并从JSX调用它,但是我们如何在react-native本机UI组件中做同样的事情?
It's clear to me that for react-native native modules we can use the @ReactMethod
to export a method and call it from JSX, but how do we do the same thing in react-native native UI components?
在文档中,我只看到提到了@ReactProp
.
如果@ReactMethod
不起作用,那么如何从JSX访问本机UI组件的属性呢? (在iOS上,可以使用RCT_EXPORT_METHOD
在本机ui组件上完成此操作,但在Android上可以实现类似的操作吗?)
In the documentation I only see @ReactProp
being mentioned.
If @ReactMethod
is not working, how do I access a property of my native UI component from JSX then? (On iOS this can be done on native ui components with RCT_EXPORT_METHOD
but on Android is something similar possible?)
谢谢.
推荐答案
好,我最终创建了一个模块,并在其构造函数上传递了UI组件引用:
Ok I ended up creating a Module, and passing a UI Component reference on it's constructor:
这是我的 UI组件:
public class RCTACCalendarManager extends ViewGroupManager <RCTACCalendar> {
public static final String REACT_CLASS = "RCTACCalendar";
private RCTACCalendar calendarInstance;
public RCTACCalendarManager(ReactApplicationContext reactContext) {
super();
}
@Override
public String getName() {
return REACT_CLASS;
}
@Override
public RCTACCalendar createViewInstance(ThemedReactContext context) {
calendarInstance = new RCTACCalendar(context);
return calendarInstance;
}
public RCTACCalendar getCalendarInstance() { // <-- returns the View instance
return calendarInstance;
}
}
这是我为该组件创建的模块:
Here's the Module I created for that component:
public class RCTACCalendarModule extends ReactContextBaseJavaModule {
private RCTACCalendar calendarInstance;
public RCTACCalendarModule(ReactApplicationContext reactContext, RCTACCalendarManager calManager) {
super(reactContext);
if (calManager != null) {
calendarInstance = calManager.getCalendarInstance();
}
}
@Override
public String getName() {
return "ACCalendarManager";
}
@ReactMethod
public void mySuperDuperFunction(Promise promise) {
if (calendarInstance != null) {
calendarInstance.mySuperDuperFunction(promise); // <-- Magic
}
}
}
,这是我在 Package 声明中将这两者结合在一起的方法:
and here's how I combine those two together in my Package declaration:
public class RCTACCalendarPackage implements ReactPackage {
private RCTACCalendarManager calManager;
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
if (calManager == null) {
calManager = new RCTACCalendarManager(reactContext);
}
return Arrays.<NativeModule>asList(
new RCTACCalendarModule(reactContext, calManager)
);
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
if (calManager == null) {
calManager = new RCTACCalendarManager(reactContext);
}
return Arrays.<ViewManager>asList(
calManager
);
}
}
它就像一种魅力.
这篇关于如何在Android中实现React Native UI组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!