the*_*rty 11 typescript reactjs react-router
我正在尝试将一个小型反应应用程序移植到打字稿上.
我遇到了react-router的问题.我有明确类型的最新定义,但以下代码给出了错误:
var routes:Router.Route = (
<Route name="root" path="/" handler={MyApp}>
<Route path="dashboard" handler={MyDash} />
<DefaultRoute handler={SomeSection} />
<NotFoundRoute handler={NotFoundPage} />
</Route>
);
Router.run(routes, function (Handler:React.Component<any, any>) {
React.render(<Handler/>, document.body);
});
Run Code Online (Sandbox Code Playgroud)
这些是我得到的编译错误:
js/app.tsx(31,3): error TS2605: JSX element type 'Component<RouteProp, any>' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Component<RouteProp, any>'.
js/app.tsx(32,5): error TS2605: JSX element type 'Component<RouteProp, any>' is not a constructor function for JSX elements.
js/app.tsx(47,5): error TS2605: JSX element type 'Component<DefaultRouteProp, any>' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Component<DefaultRouteProp, any>'.
js/app.tsx(49,5): error TS2605: JSX element type 'Component<NotFoundRouteProp, any>' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Component<NotFoundRouteProp, any>'.
js/app.tsx(53,20): error TS2345: Argument of type '(Handler: Component<any, any>) => void' is not assignable to parameter of type '(Handler: RouteClass, state: RouterState) => void'.
Types of parameters 'Handler' and 'Handler' are incompatible.
Type 'Component<any, any>' is not assignable to type 'RouteClass'.
js/app.tsx(54,17): error TS2604: JSX element type 'Handler' does not have any construct or call signatures.
Run Code Online (Sandbox Code Playgroud)
使用typescript初始化一组react-router路由的正确方法是什么?
(我应该澄清一下,我正在使用通过--jsx react旗帜支持JSX的夜间打字稿
Rya*_*ugh 15
根本问题是react-router中的一些定义没有显式的render()方法.这已通过https://github.com/borisyankov/DefinitelyTyped/pull/5197(间接)修复
请注意,此代码不正确:
Router.run(routes, function (Handler:React.Component<any, any>) {
React.render(<Handler/>, document.body);
});
Run Code Online (Sandbox Code Playgroud)
它应该是:
Router.run(routes, function (Handler: new() => React.Component<any, any>) {
React.render(<Handler/>, document.body);
});
Run Code Online (Sandbox Code Playgroud)
因为Handler是React组件的构造函数,而不是它的实例.
类型定义中的错误似乎是原因。您可以通过修改文件来解决这些问题,.d.ts如下所示:
在 中,从界面中react.d.ts删除renderJSX.ElementClass
interface ElementClass extends React.Component<any, any> {
}
Run Code Online (Sandbox Code Playgroud)
在 中react-router.d.ts,将run方法的routes参数类型更改为React.ReactElement<RouteProp>
function run(routes: React.ReactElement<RouteProp>, callback: RouterRunCallback): Router;
function run(routes: React.ReactElement<RouteProp>, location: LocationBase, callback: RouterRunCallback): Router;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11185 次 |
| 最近记录: |