JSX元素类型'ReactElement <any>不是JSX元素的构造函数。类型'undefined'不能分配给类型'Element |空值'

时间:2020-09-18 18:46:45

标签: javascript reactjs typescript create-react-app

我尝试了建议的解决方案,即删除node_modules/yarn.lock并重新安装所有内容,但并不能解决问题。

我正在制作一个简单的路由器,该路由器根据道具渲染孩子:

import React, { Fragment } from "react";

type RouterProps = {
  currentRoute: string;
  children: React.ReactNode;
};

const Router = ({ currentRoute, children }: RouterProps) => {
  return React.Children.map(children, child =>
    React.cloneElement(child as React.ReactElement<any>, { currentRoute })
  );
};

type RouterViewProps = {
  route: string;
  children: any;
};

Router.View = ({ route, currentRoute, children }: RouterViewProps) => (
  <div>{currentRoute === route ? <Fragment>{children}</Fragment> : null}</div>
);

export default Router;

尝试在应用程序中使用我的组件时出现错误:

import React from "react";
import Router from "./components/Router";
import Home from "./components/Home";

function App() {
  return (
    <div>
      <Router currentRoute="home">
        <Router.View route="home">
          <Home />
        </Router.View>
      </Router>
    </div>
  );
}

export default App;

完整错误:

TypeScript error in /Users/gonzo/Projects/JS/filex-workshops-registration/src/App.tsx(8,7):
JSX element type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any
, any>)>[] | null | undefined' is not a constructor function for JSX elements.
  Type 'undefined' is not assignable to type 'Element | null'.  TS2605

     6 |   return (
     7 |     <div>
  >  8 |       <Router currentRoute="home">
       |       ^
     9 |         <Router.View route="home">
    10 |           <Home />
    11 |         </Router.View>

路由器组件在我的测试中可以很好地工作,所以我不了解应用程序本身有什么不同。

1 个答案:

答案 0 :(得分:1)

Router不是JSX的构造函数,因为它不返回JSX。

const Router = ({ currentRoute, children }: RouterProps) => {
  return (
    <>
       {React.Children.map(children, child =>
          React.cloneElement(child as React.ReactElement<any>, { currentRoute })
       )}
    </>
  );
};