想要在原生代碼里獲取RN的View悬包,就像原生代碼里的findViewById焕数,然后就可以在原生代碼里調用view的一些函數(shù)笙什,比如一些get方法吨悍,然后數(shù)據回調給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)荠藤。