当前分析的ReactNative版本为0.61.5:
一、ViewManager定义
首先我们来看ViewManager的定义:
/**
* Class responsible for knowing how to create and update catalyst Views of a given type. It is also
* responsible for creating and updating CSSNodeDEPRECATED subclasses used for calculating position
* and size for the corresponding native view.
*/
@ReactPropertyHolder
public abstract class ViewManager<T extends View, C extends ReactShadowNode>
extends BaseJavaModule {
}
我们看到它本质上是NativeModule,并且它管理着自定义的View。它提供如下功能:
1.修改View公有属性;
2.创建View;
3.创建View的ShadowNode(View的整体布局大小);
4.View生命周期的监听,比如onDropViewInstance;
5.View初始化属性后调用onAfterUpdateTransaction;
我们看到,核心功能就是对View的管理,包含创建,销毁的监听等。
另外还有一个方法如下:
/**
* Subclasses may use this method to receive events/commands directly from JS through the {@link
* UIManager}. Good example of such a command would be {@code scrollTo} request with coordinates
* for a {@link ScrollView} instance.
*
* <p>This method is deprecated use {@link #receiveCommand(View, String, ReadableArray)} instead.
*
* @param root View instance that should receive the command
* @param commandId code of the command
* @param args optional arguments for the command
*/
@Deprecated
public void receiveCommand(@NonNull T root, int commandId, @Nullable ReadableArray args) {
}
/**
* Subclasses may use this method to receive events/commands directly from JS through the {@link
* UIManager}. Good example of such a command would be {@code scrollTo} request with coordinates
* for a {@link ReactScrollView} instance.
*
* @param root View instance that should receive the command
* @param commandId code of the command
* @param args optional arguments for the command
*/
public void receiveCommand(@NonNull T root, String commandId, @Nullable ReadableArray args) {
}
代码如上,接收来自JS层对View的操作的命令,可以定义对View的操作,然后提供给JS层调用。
另外还会给JS暴露静态常量,如下:
/**
* Returns a map of view-specific constants that are injected to JavaScript. These constants are
* made accessible via UIManager.<ViewName>.Constants.
*/
public @Nullable Map<String, Object