【问题标题】:How to type elements in React Router v6 correctly?如何在 React Router v6 中正确输入元素?
【发布时间】:2022-10-20 22:38:00
【问题描述】:

我有一个关于输入 React Router 的问题。 我已经声明了一个接口 IRoute 来输入路由

import Event from "../pages/Event";
import Login from "../pages/Login";

export enum RouteNames {
    LOGIN = "./login",
    EVENT = "/",
  }
  
export interface IRoute {
  path: string;
  element: React.ComponentType;
}

export const publicRoutes: IRoute[] = [
  { path: RouteNames.LOGIN, element: Login },
];

export const privateRoutes: IRoute[] = [
  { path: RouteNames.EVENT, element: Event },
];

然后在 AppRouter 组件中,我想遍历 privateRoutes 和 publicRoutes:

const AppRouter: FC = () => {
  const isAuth = true;

  return (
    <div>
      {isAuth ? (
        <Routes>
          {privateRoutes.map((route) => (
            <Route path={route.path} element={route.element} />
          ))}
        </Routes>
      ) : (
        <Routes> 
          {publicRoutes.map((route) => (
            <Route path={route.path} element={route.element} /> // throws an error here
          ))}</Routes>
      )}
    </div>

我收到以下错误:

Type 'ComponentType<{}>' is not assignable to type 'ReactNode'.
  Type 'ComponentClass<{}, any>' is not assignable to type 'ReactNode'.ts(2322)
components.d.ts(52, 5): The expected type comes from property 'element' which is declared here on type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'

谁能帮我在这里正确输入所有内容?谢谢!

【问题讨论】:

  • 你能分享publicRoutesprivateRoutes数组吗?
  • 他们在第一个sn-p

标签: reactjs typescript react-router


【解决方案1】:

元素应该像标签一样被提及,

    import Login from "../pages/Login";
    export const publicRoutes: IRoute[] = [
      { path: RouteNames.LOGIN, element: <Login /> },
    ];

导入登录组件并像上面一样提供它。

【讨论】:

  • 'Login' refers to a value, but is being used as a type here. Did you mean 'typeof Login?' ts(2749) - 如果我将 Login 放在标签中,TypeScript 会抛出错误。因此,我在 AppRouter 中添加了这样的标签:&lt;Route path={route.path} element={&lt;route.element /&gt;} /&gt;,但只有当我将“元素”类型更改为“任何”时,应用程序才开始工作。也许你可以告诉我如何正确输入这个元素!
【解决方案2】:

检查您的文件扩展名,它应该是“tsx”。 我认为这就是 jsx/tsx 语法不起作用的原因。

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 2022-01-23
    • 2022-01-23
    • 1970-01-01
    • 2021-12-20
    • 2022-01-17
    • 2022-11-19
    • 2021-12-25
    • 2023-01-17
    相关资源
    最近更新 更多