【问题标题】:TypeScript React Functional Component - is missing the following properties from type 'Element': type, props, key errorTypeScript React 功能组件 - 缺少“元素”类型的以下属性:类型、道具、键错误
【发布时间】:2021-05-11 02:27:20
【问题描述】:

我有以下定义:

IRoute:


export interface IRoute{
    key: string, 
    path: string,
    exact: boolean,
    component: JSX.Element,
    private?: boolean
}

IRoutesConfig:

import { IRoute } from "./IRoute";

export default interface IRoutesConfig {
    [key : string] : [IRoute]
}

还有我的Routes Configration,然后我会将其传递给一个类以进行进一步的增强

import Login from "../container/Auth/Login/Login";
import IRoutesConfig from "./IRoutesConfig";

const Routes : IRoutesConfig = {
    "Auth": [
        {
            key: "login-page",
            exact: true, 
            component: Login,
            path: "/auth/login"
        }
    ]
}

export default Routes;

我正在使用登录功能组件进行测试:

import React, { FC, ReactElement } from 'react';

type LoginProps = {

}

const Login : FC<LoginProps> = (props) : ReactElement => {
  return (
    <>
    
    </>
  );
}

export default Login;

这是一个新的项目设置,还没有为登录道具定义任何东西。所以它目前是空的,稍后会扩展,内容也是如此,因为我们目前正在设置路由架构。

VSCode 在Routes:IRoutesConfig 中就“component”给了我以下提示:

当然我不是在声明类型、props 和 key。

最后,路由配置将被提供给 RouteManager,它将为 `React-Router-Dom' 的 Switch 动态创建 Routes,以及其他一些内容,具体取决于我访问它的位置。

它将创建一个路线图,例如:

<Route key="login-page" path="/auth/login" component={Login} />

然后在反应容器组件中使用:

...

let authRoutes = RoutesManager.getAllRoutes("Auth");

return (
    <Switch>
      {authRoutes}
      <Redirect key="account-redirect" to="/account" />
    </Switch>
  );

问题: 据我了解,react-router-dom route 期望它的 arg componentJSX.element,但是我的 Login 功能组件的返回类型是 ReactElement。据我了解,JSX.element 在这种情况下是一个通用的 ReactElement。 Login FC 将有子代。

如何解决将登录 FC 正确传递给配置的问题,以便稍后由 react-router-dom 的路由组件使用?

【问题讨论】:

    标签: reactjs typescript react-router-dom


    【解决方案1】:

    据我了解,错误来自component: JSX.Element。您正在尝试通过将private 属性添加到Route 来创建受保护的路由。您可以更改 IRoute 接口以扩展 react-router 定义的类型,这样您就不会再遇到这个问题了。

    首先:添加此导入语句。

    import { RouteProps } from "react-router-dom";
    

    第二个:将您的IRoute 接口更改为:

    export interface IRoute extends RouteProps{
        private?: boolean
    }
    

    这样,您只需告诉我的IRoute 具有所有简单的Route 属性加上private

    【讨论】:

    • 谢谢,这让事情变得容易多了。我认为我的组件声明很简单,因为 RouteProps 实际上将组件定义为 "(property) RouteProps.component?: React.ComponentClass, any> | React.FunctionComponent> | React.ComponentClass<...> | React.FunctionComponent<...> | 未定义”。
    • @Richard 是的,乍一看,您的声明很简单。但是每种类型的组件都有自己的优缺点,可能会迫使您拥有一些您不需要的属性。 RouteProps 接受所有有效的组件类型,因此当您想使用没有道具的组件时,您不会遇到困难。
    猜你喜欢
    • 2020-02-07
    • 2021-01-05
    • 2020-12-20
    • 2021-06-24
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2015-12-02
    • 2020-05-30
    相关资源
    最近更新 更多