react-native-webview Typescript 错误:“WebView”无法用作 JSX 组件

2024-01-11

我正在尝试使用 Expo 和 TypeScript 来设置一个简单的 React Native 应用程序,以显示 WebView。我的App.tsx文件包含以下内容:

import Constants from 'expo-constants';
import { StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';

export default function App() {
    return (
        <WebView
            style={styles.container}
            source={{ uri: 'https://example.com/' }}
        />
    );
}

const styles = StyleSheet.create({
    container: {
        marginTop: Constants.statusBarHeight,
    },
});

此代码可以正常工作,但 TypeScript 编译器会在 WebView 组件中引发错误。

App.tsx:7:4 - error TS2786: 'WebView' cannot be used as a JSX component.
  Its instance type 'WebView<{ style: { marginTop: number; }; source: { uri: string; }; }>' is not a valid JSX element.
    The types returned by 'render()' are incompatible between these types.
      Type 'import("C:/example/node_modules/@types/react/index").ReactNode' is not assignable to type 'React.ReactNode'.
        Type '{}' is not assignable to type 'ReactNode'.
          Type '{}' is missing the following properties from type 'ReactPortal': key, children, type, props

7   <WebView
     ~~~~~~~


Found 1 error.

我正在使用以下版本的依赖项:

{
    "dependencies": {
        "expo": "~44.0.0",
        "expo-status-bar": "~1.2.0",
        "react": "17.0.1",
        "react-dom": "17.0.1",
        "react-native": "0.64.3",
        "react-native-web": "0.17.1",
        "react-native-webview": "11.15.0"
    },
    "devDependencies": {
        "@babel/core": "^7.12.9",
        "@types/react": "~17.0.21",
        "@types/react-native": "~0.64.12",
        "typescript": "~4.3.5"
    }
}

我该如何纠正这个错误?


如果您有多个,您会收到此错误@types/react你的图书馆node_modules。就我而言,这是由 Storybook 引起的,其中包括 @reach/router,其中包括 @types/reach__router,其中包括 @types/react@18,与我当前的 Expo 版本不同。

Using 如何使用“yarn”覆盖嵌套依赖项? https://stackoverflow.com/questions/40226639/how-do-i-override-nested-dependencies-with-yarn

我添加了匹配的版本

  "resolutions": {
    "@types/react": "~17.0.21"
  },

并重新生成以消除错误。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

react-native-webview Typescript 错误:“WebView”无法用作 JSX 组件 的相关文章

随机推荐