Programmatically navigate using react router

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

    based on the previous answer
    from José Antonio Postigo and Ben Wheeler
    the novelty? is to be written in Typescript
    and the use of decorators
    OR static property/field

    import * as React from "react";
    import Component = React.Component;
    import { withRouter } from "react-router";
    
    export interface INavigatorProps {
        router?: ReactRouter.History.History;
    }
    
    /**
     * Note: goes great with mobx 
     * @inject("something") @withRouter @observer
     */
    @withRouter
    export class Navigator extends Component{
        navigate: (to: string) => void;
        constructor(props: INavigatorProps) {
            super(props);
            let self = this;
            this.navigate = (to) => self.props.router.push(to);
        }
        render() {
            return (
                
    • this.navigate("/home")}> Home
    • this.navigate("/about")}> About
    ) } } /** * Non decorated */ export class Navigator2 extends Component { static contextTypes = { router: React.PropTypes.object.isRequired, }; navigate: (to: string) => void; constructor(props: INavigatorProps, context: any) { super(props, context); let s = this; this.navigate = (to) => s.context.router.push(to); } render() { return (
    • this.navigate("/home")}> Home
    • this.navigate("/about")}> About
    ) } }

    with whatever npm installed today. "react-router": "^3.0.0" and
    "@types/react-router": "^2.0.41"

提交回复
热议问题