【RN-ReactFindViewUtil】根据nativeID

作者: zsgnaw | 来源:发表于2019-04-29 11:26 被阅读7次

想要在原生代码里获取RN的View,就像原生代码里的findViewById,然后就可以在原生代码里调用view的一些函数,比如一些get方法,然后数据回调给RN或者做一些其他操作。
找到如下属性:


image.png

但是不会用。。。

通过原生UI组件封装的源码查看:SimpleViewManager -> BaseViewManager,
在BaseViewManager里找到了PROP_NATIVE_ID(nativeID)的属性设置方法,然后找到了ReactFindViewUtil类。

  @ReactProp(name = PROP_NATIVE_ID)
  public void setNativeId(T view, String nativeId) {
      view.setTag(R.id.view_tag_native_id, nativeId);
      ReactFindViewUtil.notifyViewRendered(view);
  }

最后通过ReactFindViewUtil中的方法可以找到View实例。

/**
   * Finds a view that is tagged with {@param nativeId} as its nativeID prop
   * under the {@param root} view hierarchy. Returns the view if found, null otherwise.
   * @param root root of the view hierarchy from which to find the view
   */
  public static @Nullable View findView(View root, String nativeId) {
    String tag = getNativeId(root);
    if (tag != null && tag.equals(nativeId)) {
      return root;
    }
    if (root instanceof ViewGroup) {
      ViewGroup viewGroup = (ViewGroup) root;
      for (int i = 0; i < viewGroup.getChildCount(); i++) {
        View view = findView(viewGroup.getChildAt(i), nativeId);
        if (view != null) {
          return view;
        }
      }
    }
    return null;
  }

  /**
   * Finds a view tagged with {@param onViewFoundListener}'s nativeID in the given {@param root}
   * view hierarchy. If the view does not exist yet due to React Native's async layout, a listener
   * will be added. When the view is found, the {@param onViewFoundListener} will be invoked.
   * @param root root of the view hierarchy from which to find the view
   */
  public static void findView(View root, OnViewFoundListener onViewFoundListener) {
    View view = findView(root, onViewFoundListener.getNativeId());
    if (view != null) {
      onViewFoundListener.onViewFound(view);
    }
    addViewListener(onViewFoundListener);
  }

root直接用getCurrentActivity().getWindow().getDecorView()就行。RN代码中nativeID注意大小写(nativeid、nativeId)。

相关文章

  • 【RN-ReactFindViewUtil】根据nativeID

    想要在原生代码里获取RN的View,就像原生代码里的findViewById,然后就可以在原生代码里调用view的...

  • 根据

    看似简简单单的两个字,昨晚让我翻来覆去睡不着。今年迷失了自己,找不到与人相处的方式。 领导问话固然紧张,但是看到领...

  • 根据内

    // 根据内容自适应单元格的高度//先得到内容NSDictionary *dic=self.allDataArra...

  • 根据UIViewContentModeScaleAspectFi

    最近在开发需要给图片切圆角,正常来说是按照固定的大小来进行裁剪圆角,但是由于业务原因,图片无法提供固定的大小而且要...

  • 根据地

    这次脚伤恢复得好慢,从过年回家到现在四个多月了,才刚刚开始消肿,经历了一段时间的迷茫与沉沦,我开始坐下来重新审视自...

  • 根据权重抽奖..

    根据用户名(id)和权重抽奖 test_model运行结果 权重: 1 此权重中奖次数: 49514权重: 2 此...

  • 根据需求选择

    面对不同人群,我们该主推哪些险种? 2017.06.李娟 重大疾病保险,是指当被保险人患保单指定的重大疾病确诊后,...

  • 根据地

    我们第一个阵法,它是相对比较单纯,直接地立过来,相当于一个人心口直快,有什么说什么,没有藏着掖着,这种人非常值得交...

  • 根据地

    开店办厂如果租来的厂房和店面,生意兴旺时间久之,房主店主不是加租,也是要回自用。要开店办厂,厂房店面要有,有的平台...

  • 根据颜色排队

    坐磁悬浮列车去东京机场,在等候区的地面上有两种颜色标注排队,蓝色是马上就到的车次,红色是下一趟到达的列车,这样可以...

网友评论

    本文标题:【RN-ReactFindViewUtil】根据nativeID

    本文链接:https://www.haomeiwen.com/subject/sfaenqtx.html