ReactNative源码分析之ViewManager

本文分析了ReactNative 0.61.5版本中的ViewManager,揭示了其作为NativeModule管理自定义View的核心功能,包括设置View属性、创建与销毁、生命周期监听及与JS层交互。在RN框架中,ViewManager通过ReactPackage接口在ReactInstanceManager中注册,并在UIManagerModule中被用于处理JS层对View的操作。
摘要由CSDN通过智能技术生成

当前分析的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值