【问题标题】:React router with typescript用打字稿反应路由器
【发布时间】:2019-01-20 07:36:36
【问题描述】:

我正在使用 react-routerreact-router-dom 和 Typescript 来构建应用程序。我以这种方式定义了我的路线(routes.tsx):

import * as React from 'react';
import createBrowserHistory from 'history/createBrowserHistory';
import { Router, Route, Switch } from 'react-router-dom';
import SignUp from '../routes/signup';

const history = createBrowserHistory();

const Routes: React.StatelessComponent<{}> = () => (
  <Router history={history}>
    <Switch>
      <Route exact path='/signup' component={SignUp} />
    </Switch>
  </Router>
);

export default Router;

我有一个主要的App 组件来呈现这个Routes 组件:

import * as React from 'react';
import Routes from './routes';

const App: React.StatelessComponent<{}> = () => (
  <Routes />
);

export default App;

编译器抛出此错误

(5,4): Type '{}' is not assignable to type 'Readonly<RouterProps>'.
  Property 'history' is missing in type '{}'.

我是 TS 新手,所以我不确定到底发生了什么。

【问题讨论】:

  • 我认为export default Router; 应该是export default Routes;

标签: reactjs typescript react-router react-router-dom


【解决方案1】:

TypeScript 与大多数语言一样,需要在类上的 &lt; &gt; 标记之间使用类型说明符。这表明该类是一个泛型,需要进一步定义。

我无法找到有关您正在使用的此类的特定文档,但我想这样的内容可能会帮助您找到正确的地方:

const App: React.StatelessComponent<RouterProps> = () => (
  <Routes />
);

【讨论】:

  • 这很接近,但它说RouterProps 不是通用的。
猜你喜欢
  • 2018-09-29
  • 1970-01-01
  • 2023-01-03
  • 2017-11-09
  • 2017-10-30
  • 2022-11-25
  • 2021-07-15
  • 2022-10-05
  • 2019-11-03
相关资源
最近更新 更多