Trying to rewrite ReactJS's config based router example to be used with TypeScript and have an issue in defining an appropriate type.
(试图重写与TypeScript一起使用的ReactJS基于config的路由器示例 ,并且在定义合适的类型时遇到问题。)
I have the following array of routes in file routes.ts
:
(我在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;
And the following function component:
(和以下功能组件:)
export function RouteWithSubRoutes(route: Routes): JSX.Element {
return (
<Route
key={route.path}
path={route.path}
>
{(): JSX.Element => <route.component routes={route.routes} />}
</Route>
);
}
When I define Routes
type as following:
(当我如下定义Routes
类型时:)
export type Routes = {
path: string;
component: Function;
routes?: Routes[];
}
everything works fine.
(一切正常。)
But If I try to be more specific, at the end function return type JSX.Element
it just doesn't work. (但是,如果我尝试更具体一点,最后,函数返回类型为JSX.Element
就是行不通的。)
I've tried the following: (我尝试了以下方法:)
import React, { FunctionComponent } from 'react';
export type Routes = {
path: string;
component: FunctionComponent;
routes?: Routes[];
}
and
(和)
import React, { FunctionComponent } from 'react';
export type Routes = {
path: string;
component: React.FC;
routes?: Routes[];
}
and of course:
(而且当然:)
export type Routes = {
path: string;
component: JSX.Element;
routes?: Routes[];
}
In all cases I get the following errors:
(在所有情况下,我都会遇到以下错误:)
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
And have no idea what's going wrong.
(而且不知道出了什么问题。)
ask by Anatoly translate from so