typescript 如何修复'JSX元素类型'组件'没有任何构造或调用签名'在ts

llycmphe  于 2023-03-19  发布在  TypeScript
关注(0)|答案(2)|浏览(213)

我用这样的路由器。
我从路由中获取“组件”,但ts抛出错误,在js中,没有错误。

import React from "react";
import { Route, Switch, useRouteMatch, withRouter } from "react-router-dom";
import type { MyRoute } from "./types";

const routes: MyRoute[] = [
  {
    path: "overview",
    Component: Index,
    title: "概览",
    name: "index",
    requireAuth: false,
  }
];

const MainRoute: React.FunctionComponent = () => {
  const match = useRouteMatch();
  const filter = (route: MyRoute): JSX.Element => {
    const { Component } = route;
    return (
      <Route
        key={route.path}
        path={`${match.path}/${route.path}`}
        exact
        render={(props) => {
          document.title = route.title;
          // throw error in this line:JSX element type 'Component' does not have any construct or call signatures.
          return <Component {...props} />;
        }}
      />
    );
  };
  return (
        <Switch>{routes.map(filter)}</Switch>);
};

export default withRouter(MainRoute);

出现错误:JSX element type 'Component' does not have any construct or call signatures.我如何修复它

66bbxpm5

66bbxpm51#

您需要更改:

Component?: JSX.Element | React.ReactNode | React.FunctionComponent;

致:

Component?: React.FunctionComponent;

类型为MyRoute
为什么?JSX.Element它就像<div>jsx element<div>,但是你的组件必须是一个React组件,例如函数。

rt4zxlrg

rt4zxlrg2#

export interface MyRoute {
  path: string;
  Component?: JSX.Element | React.ReactNode | React.FunctionComponent;
  title: string;
  name: string;
  requireAuth?: boolean;
  children?: MyRoute[];
}

相关问题