注意,這篇文章討論的是原生組件(Native UI Components),而不是原生模塊(Native Modules)。其次,我會假設你已經對原生組件封裝有基本的了解,如果還不了解,請看官方文檔:Android 篇,iOS 篇。
開始
也許你并不知道,除了 props,RN 還提供另一種直接調用原生組件方法的機制,通過這種機制,就可以實現 react 組件方法(Refs and the DOM)。內置的原生組件就有這樣的實現:ScrollView#scrollTo、DrawerLayoutAndroid#openDrawer。然而官方文檔并沒有相關的描述,不過,我們還是可以通過研究內置組件的實現代碼,作出一些總結。
廢話不多說,直接上結論,下面以 ScrollView#scrollTo
為例
Component
ScrollView.js
:
// @flow
import React, {PureComponent} from 'react'
import {findNodeHandle, UIManager} from 'react-native'
export default class ScrollView extends PureComponent {
_sendCommand(command: string, params?: []) {
UIManager.dispatchViewManagerCommand(
findNodeHandle(this),
UIManager.RNScrollView.Commands[command],
params,
)
}
scrollTo(y: number) {
this._sendCommand('scrollTo', [y])
}
}
-
UIManager.dispatchViewManagerCommand
用于發送命令到原生組件 - 第1個參數是 component ref
- 第2個參數是 command ref,格式為
UIManager[Component].Commands[command]
- 第3個參數是 command params,必須是數組
Android
ScrollViewManager.java
:
public class ScrollViewManager extends ViewGroupManager<ScrollView> {
public static final int SCROLL_TO = 1;
@Override
public @Nullable Map<String, Integer> getCommandsMap() {
return MapBuilder.of("scrollTo", SCROLL_TO);
}
@Override
public void receiveCommand(ScrollView root, int commandId, @Nullable ReadableArray args) {
if (commandId == SCROLL_TO) {
root.scrollTo(args);
}
}
}
- 通過
getCommandsMap
定義命令映射,這個映射也就是 js 端的UIManager[Component].Commands[command]
- 在
receiveCommand
里處理命令,js 端傳過來的 params 會被轉換成 ReadableArray
iOS
ScrollViewManager.m
:
RCT_EXPORT_METHOD(scrollTo:(nonnull NSNumber *)reactTag y:(NSInteger)y) {
ScrollView *scrollView = (ScrollView *) viewRegistry[reactTag];
scrollView.scrollTo(y);
}
iOS 就更簡單了,我想已經不需要做太多解釋。
最后
有一點需要注意:原生組件的命令機制不能返回數據。不過,退而求其次,可以通過事件的方式向 js 端回傳數據。
如果你還是不太確定怎么實現,那么建議你去看 RN 內置組件的源代碼。