BrowserRouter 与typescriptreact

IT技术 reactjs typescript
2021-05-19 06:11:02

我在 Reactjs + 类型脚本中有简单的应用程序。我正在尝试使用 react-router-dom 中的 BrowserRouter。

这是我的代码:

import * as React from "react"

import { Popular } from "./popular"

import { BrowserRouter as Router, Route } from "react-router-dom"

export interface AppProp {

}

export interface AppState {

}
export class App extends React.Component<AppProp , AppState > {

    render() {
        return (

            <div className='container'>
                <Router>
                    <Route path='/popular' component={Popular} />
                </Router>
            </div>
        )
    }
}

export default App

我收到以下错误:

[at-loader] ./node_modules/@types/react-router-dom/index.d.ts:55:25 TS2314 中的错误:通用类型“组件”需要 2 个类型参数。

[at-loader] ./src/components/app.tsx:25:18 TS2604 中的错误:JSX 元素类型“路由器”没有任何构造或调用签名。

我在谷歌搜索但没有任何帮助。

有人有想法吗?

BR纳达夫

2个回答

好像是打字问题

如果您使用的是 TypeScript 2.4.1,请确保您使用的是 @types react 的那些版本。

"@types/react": "15.0.35",
"@types/react-dom": "15.5.1",

我能够将 BrowserRouter 与 typescript 一起使用,并且能够将历史props和我的 redux props/thunk 传递给我的组件。关键是在应用程序级别使用“withRouter”。我还必须使用带有“Route”的渲染属性来获取我的props。我现在可以在我的组件以及我的props和 thunk 中使用“this.props.history.push("/url1")”和“this.props.history.replace("/url2")”。传播符号也很摇滚。

import { RouteComponentProps, withRouter,
         Switch, Route, Redirect } from 'react-router-dom'

interface AppProps {
  children?: any
  myAppStore: any
  myAppActions: any
};

class App extends React.Component<RouteComponentProps<{}> & AppProps>
{
  constructor(props: RouteComponentProps<{}> & AppProps) {
  super(props);
 }

render() {
  return (
    <div className="App">
      <AppNavBar {...this.props}/>
      <Switch>

        // This component gets both Router props and my props
        <Route path="/c1" default={true} exact={true} render={()=>{return( 
           <MyComponentOne {...this.props}/>)} } />

        // This component only gets Router props
        <Route path="/c2" {...this.props} exact={true} component={MyComponentTwo } />

        </Switch>
        <Redirect from="/" to="/c1"/>
      </div>
    );
  }
}

... Do redux stuff ..
// ApplicationProps and ApplicationActions are mapped redux props and thunks.

const connector = connect(ApplicationProps,ApplicationActions);
export default connector<any>(withRouter(App));

这是我的 index.tsx 渲染

  <Provider store={MyStore}>
  <BrowserRouter basename="/">
  <App/>
  </BrowserRouter>
  </Provider>