BrowserRouter in react with typescript

前端 未结 2 493
野趣味
野趣味 2021-01-26 12:16

I have simple application in Reactjs + type script. I\'m trying to use the BrowserRouter from react-router-dom.

This is my code :

import * as React from          


        
相关标签:
2条回答
  • 2021-01-26 12:44

    It seems to be Typings problem,

    If you are using TypeScript 2.4.1, make sure you are using those versions of @types react.

    "@types/react": "15.0.35",
    "@types/react-dom": "15.5.1",
    
    0 讨论(0)
  • 2021-01-26 12:52

    I was able to use BrowserRouter with typescript and was able to pass both the history prop and my redux props/thunks down to my components. The key was to use 'withRouter' at the app level. I also had to use the render property with "Route" to get my props down. I can now use "this.props.history.push("/url1")" and "this.props.history.replace("/url2")" in my components as well as my props and thunks. Also the spread notation rocks.

    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));
    

    This is my index.tsx render

      <Provider store={MyStore}>
      <BrowserRouter basename="/">
      <App/>
      </BrowserRouter>
      </Provider>
    
    0 讨论(0)
提交回复
热议问题