Programmatically navigate using react router

后端 未结 30 2298
無奈伤痛
無奈伤痛 2020-11-21 05:18

With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls t

30条回答
  •  被撕碎了的回忆
    2020-11-21 05:43

    May not be the best approach but... Using react-router v4, the following Typescript could give an idea for some.

    In the rendered component below, e.g. LoginPage, router object is accessible and just call router.transitionTo('/homepage') to navigate.

    Navigation code was taken from.

    "react-router": "^4.0.0-2", "react": "^15.3.1",

    import Router from 'react-router/BrowserRouter';
    import { History } from 'react-history/BrowserHistory';
    import createHistory from 'history/createBrowserHistory';
    const history = createHistory();
    
    interface MatchWithPropsInterface {
      component: typeof React.Component,
      router: Router,
      history: History,
      exactly?: any,
      pattern: string
    }
    
    class MatchWithProps extends React.Component {
      render() {
        return(
           (
                 React.createElement(this.props.component, this.props)
    
            )}
           />
        )
      }
    }
    
    ReactDOM.render(
        
          {({ router }) => (
            
    )}
    , document.getElementById('app') );

提交回复
热议问题