繁体   English   中英

如何为路由器对象定义类型,该类型需要传递给ReactJS中的功能组件?

[英]How do I define type for router object which I need to pass to the function component in ReactJS?

试图重写与TypeScript一起使用的ReactJS基于config的路由器示例 ,并且在定义合适的类型时遇到问题。

我在routes.ts文件中有以下路由数组:

import Module1 from './modules/module-1';
import SubModule1 from './modules/sub-module-1';
import SubModule2 from './modules/sub-module-2';
import { Routes } from './routes.d';

const routes: Routes[] = [
  {
    path: '/module1',
    component: Module1,
    routes: [
      {
        path: '/module1/submodule1',
        component: SubModule1,
      },
      {
        path: '/module1/submodule2',
        component: SubModule2,
      },
    ],
  }
];


export default routes;

和以下功能组件:

export function RouteWithSubRoutes(route: Routes): JSX.Element {
  return (
    <Route
      key={route.path}
      path={route.path}
    >
      {(): JSX.Element => <route.component routes={route.routes} />}
    </Route>
  );
}

当我如下定义Routes类型时:

export type Routes = {
  path: string;
  component: Function;
  routes?: Routes[];
}

一切正常。 但是,如果我尝试更具体一点,最后,函数返回类型为JSX.Element就是行不通的。 我尝试了以下方法:

import React, { FunctionComponent } from 'react';

export type Routes = {
  path: string;
  component: FunctionComponent;
  routes?: Routes[];
}

import React, { FunctionComponent } from 'react';

export type Routes = {
  path: string;
  component: React.FC;
  routes?: Routes[];
}

而且当然:

export type Routes = {
  path: string;
  component: JSX.Element;
  routes?: Routes[];
}

在所有情况下,我都会遇到以下错误:

error TS2322: Type '{ routes: Routes[] | undefined; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
[0]   Property 'routes' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.
[0] src/routes.ts(12,5): error TS2322: Type '(props: Routes) => Element' is not assignable to type 'FunctionComponent<{}>'.
[0]   Types of parameters 'props' and 'props' are incompatible.
[0]     Type '{ children?: ReactNode; }' is missing the following properties from type 'Routes': path, component

而且不知道出了什么问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM