简体   繁体   中英

JSX element type 'ReactElement<any> is not a constructor function for JSX elements. Type 'undefined' is not assignable to type 'Element | null'

I tried the recommended solution of deleting node_modules/ and yarn.lock and reinstalling everything but it did not solve it.

I am making a simple router that renders children based on a prop:

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;

I get the error when trying to use my component in the app:

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;

Full error:

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>

The Router component works perfectly in my tests so I don't understand what's different in the app itself.

Router is not a constructor for JSX since it does not return JSX.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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