我正在尝试使用原生 UI 组件,例如声明为 here 的组件和 here .
问题是不知道对应的native组件有没有实现。 如果我需要一个不存在的组件,像这样:
requireNativeComponent('InexistentComponent', null);
我收到这个错误:
Invariant Violation: Native component for "InexistentComponent" does not exist
用 try/catch
包装代码似乎没有任何效果:
try {
const native = requireNativeComponent('InexistentComponent', null);
return native;
} catch (_) {
return null;
}
那么有没有一种方法可以在使用 requireNativeComponent
要求组件之前查明组件是否确实存在?
最佳答案
您可以使用 NativeModules.UIManager
检查您的组件是否存在于该对象的键列表中。
例如:
import { requireNativeComponent, NativeModules } from "react-native";
let CustomComponent = null;
if ("CustomComponent" in NativeModules.UIManager) {
CustomComponent = requireNativeComponent("CustomComponent")
}
关于react-native - 检查 Native UI 组件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953434/