React Native TypeSrcript函数返回JSX.Element类型



我有一个TypeScript函数,它返回一个React NativeView

import React from "react";
import JSX, {View} from "react-native";
class DummyClass {
static getView() {
return (
<View style={{flex: 1}}/>
);
}
}
export default DummyClass;

我用这种方式调用这个函数:

import JSX from "react-native";
import DummyClass from "./util/dummy";
const DummyWrapper = () => {
return (DummyClass.getView());
};
export default DummyWrapper;

当我运行eslint时,我会收到一个警告。

5:5警告函数@typescript eslint/explicit模块边界类型缺少返回类型

所以,我需要返回一些东西。JSX.Element似乎足够合理,但这似乎并不奏效。首先,当我试图返回JSX.Element时,VSCode无法解析它,而是假装它是any。此外,它还会在调用该函数的其他地方导致错误。

因此,这样做:static getView() : JSX.Element {const DummyWrapper = () : JSX.Element => {

导致DummyCaller:出现以下错误

5:5错误任何类型值的不安全返回@typescript eslint/no不安全返回

所以现在我不确定该做什么。我已经尝试了一些其他事情,比如返回Viewtypeof ViewReact.Component(和typeof(,以及其他一些事情。我还搞砸了从哪里导入JSX。如果我从react导入,它似乎比从react-native导入更糟糕。同样在我的研究中,我发现最常见的问题是React和React Native类型已经过时,但据我所知,我使用的是最新的版本。

我的packages.json:

{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject",
"lint": "eslint -c .eslintrc.js --ext .tsx ."
},
"dependencies": {
"@dudigital/react-native-zoomable-view": "^1.0.15",
"@react-native-community/masked-view": "^0.1.10",
"@react-navigation/native": "^5.7.6",
"@react-navigation/stack": "^5.9.3",
"@types/react-native-vector-icons": "^6.4.6",
"change-case": "^4.1.1",
"expo": "~39.0.2",
"expo-status-bar": "~1.0.2",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-39.0.2.tar.gz",
"react-native-gesture-handler": "^1.8.0",
"react-native-paper": "^4.2.0",
"react-native-reanimated": "^1.13.1",
"react-native-safe-area-context": "^3.1.8",
"react-native-screens": "^2.11.0",
"react-native-tab-view": "^2.15.2",
"react-native-vector-icons": "^7.1.0",
"react-native-web": "^0.13.18"
},
"devDependencies": {
"@babel/core": "~7.9.0",
"@types/jest": "^26.0.15",
"@types/react": "^16.9.53",
"@types/react-dom": "^16.9.8",
"@types/react-native": "^0.63.27",
"@types/react-navigation": "^3.4.0",
"@types/react-redux": "^7.1.9",
"@types/react-test-renderer": "^16.9.3",
"@typescript-eslint/eslint-plugin": "^4.5.0",
"@typescript-eslint/parser": "^4.5.0",
"commonjs": "latest",
"eslint": "^7.11.0",
"eslint-plugin-jsdoc": "^30.7.3",
"eslint-plugin-prefer-arrow": "^1.2.2",
"eslint-plugin-react": "^7.21.5",
"react-native-typescript-transformer": "^1.2.13",
"requirejs": "latest",
"ts-jest": "^26.4.1",
"tslib": "^2.0.3",
"typescript": "^4.0.3"
},
"private": true
}

React应该将JSX放入全局命名空间,因此如果您不从任何地方导入它,那么返回JSX.Element应该可以。

您也可以使用import {ReactElement} from "react"并返回ReactElement

也可以将import {FunctionComponent} from "react"DummyWrapper函数本身(而不是返回类型(键入为DummyWrapper: FunctionComponent<{}>

有很多选择。

但我真的不理解在类上从static方法创建元素的用例。这似乎是一个糟糕的设计,你应该重新思考。你能把getView做成一个功能组件吗?你需要DummyClass这门课吗?

相关内容

  • 没有找到相关文章

最新更新