Programmatically navigate using react router

后端 未结 30 2296
無奈伤痛
無奈伤痛 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:40

    I tried at least 10 ways of doing this before something worked right!

    @Felipe Skinner's withRouter answer was a bit overwhelming to me, and I wasn't sure I wanted to make new "ExportedWithRouter" class names.

    Here's the simplest and cleanest way to do it, circa current React-Router 3.0.0 and ES6:

    React-Router 3.x.x with ES6:

    import { withRouter } from 'react-router';
    
    class Example extends React.Component {
       // use `this.props.router.push('/some/path')` here
    };
    
    // Export the decorated class
    export default withRouter(Example);
    

    or, if it's not your default class, export like:

    withRouter(Example);
    export { Example };
    

    Note that in 3.x.x, the component itself is using router.push, so you can pass it anything you would pass the tag, like:

       this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'
    

提交回复
热议问题