我尝试了建议的解决方案,即删除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>
路由器组件在我的测试中可以很好地工作,所以我不了解应用程序本身有什么不同。
答案 0 :(得分:1)
Router
不是JSX的构造函数,因为它不返回JSX。
const Router = ({ currentRoute, children }: RouterProps) => {
return (
<>
{React.Children.map(children, child =>
React.cloneElement(child as React.ReactElement<any>, { currentRoute })
)}
</>
);
};