Usage of the C-API Component Hybrid Solution
Note that the ArkTS component that can be used in C-API supports only leaf nodes, such as
Image, and does not support container nodes, such asStack.
Rendering an ArkTS Component in C-API
-
Implement a custom component and use it in service code.
-
Create a custom build function and use
@Builderto decorate it. Design a factory method in the build function to build a component based onComponentName. The parameter isComponentBuilderContext, which records the information required for building a component, such asComponentNameandTag. Note that the factory method needs to be wrapped by aStackcomponent. Thepositionattribute of theStackcomponent needs to be set to(0, 0)to ensure that the component is displayed in the correct position.@Builder export function buildCustomComponent(ctx: ComponentBuilderContext) { Stack() { if (ctx.componentName === MarqueeView.NAME) { MarqueeView({ ctx: ctx.rnComponentContext, tag: ctx.tag }) } } .position({ x: 0, y: 0 }) } -
Use the
wrapBuilderfunction and pass it toRNApporRNComponentContextas a parameter.RNComponentContextis a required parameter ofRNSurface.const wrappedCustomRNComponentBuilder = wrapBuilder(buildCustomRNComponent); ··· // Used as a parameter of RNApp. RNApp({ ··· wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder, ··· }) // Used as a parameter of RNComponentContext new RNComponentContext( RNOHContext.fromCoreContext(rnohCoreContext!, rnInstance), wrappedCustomRNComponentBuilder, wrapBuilder(buildRNComponentForTag), new Map(), ) -
When creating an
RNApporRNInstance, place the component name in the array and pass it as a parameter ofarkTsComponentNames.const arkTsComponentNames = [MarqueeView.NAME]; // Used as a parameter of RNApp. RNApp({ rnInstanceConfig: { ··· arkTsComponentNames: arkTsComponentNames }, ··· }) // Passed in when creating an RNInstance. await rnohCoreContext.createAndRegisterRNInstance({ ··· arkTsComponentNames: arkTsComponentNames }); -
Use
RNApporRNSurfaceto start React Native for OpenHarmony.
Using an ArkTS Component in a C-API Component
Currently, the RNOH framework supports the mounting of an ArkTS component to the C-API component.
-
Use
createArkTSComponentto create an ArkTS component.createArkTSComponentneeds to take the following parameters:tag: component tagcomponentHandle: component handle (facebook::react::ComponentHandle)componentName: component name, which must be the same as the custom ArkTS component name defined in thebuildCustomRNComponentfunction of the entry point file.
auto componentInstanceFactory = rnInstance->getComponentInstanceFactory(); auto newChildComponentInstance = componentInstanceFactory->createArkTSComponent(tag, componentHandle, componentName); -
Call the
onChildInsertedmethod of the component to insert the component.if (newChildComponentInstance != nullptr) { this->onChildInserted(newChildComponentInstance, index); }