想要在原生代码里获取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)。
网友评论