react-native - 检查 Native UI 组件是否存在

标签 react-native

我正在尝试使用原生 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/

相关文章:

javascript - 为什么 render() 在 React Native 中被调用两次?

javascript - 如何使用expo打开日历事件创建屏幕?

java - React-native 构建错误 Android - java.lang.UnsupportedClassVersionError : com/android/build/gradle/AppPlugin : Unsupported major. 次要版本 52.0

firebase:找不到变量 IDBIndex

react-native - 无法在设备上安装应用程序,请阅读上面的错误以了解详细信息

android - 是否有任何在 react-native 中实现 JavaScriptModule 的指南?

javascript - 通过导航器打开 2 次时,react-native-camera 卡住应用程序

javascript - 使用react-native在ListView中增加和减少数量

javascript - 如何在 javascript 中只保留有字母的记录?

javascript - 如何将渲染的组件保存到内存中?