![](/img/trans.png)
[英]JSX element type 'string' is not a constructor function for JSX elements. Typescript
[英]JSX element type 'ReactElement<any> is not a constructor function for JSX elements. Type 'undefined' is not assignable to type 'Element | null'
我嘗試了刪除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>
Router 組件在我的測試中完美運行,所以我不明白應用程序本身有什么不同。
Router
不是 JSX 的構造函數,因為它不返回 JSX。
const Router = ({ currentRoute, children }: RouterProps) => {
return (
<>
{React.Children.map(children, child =>
React.cloneElement(child as React.ReactElement<any>, { currentRoute })
)}
</>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.