ES6标准下react使用router跳转context.router未定义的解决

示例:

class Example extends React.Component{
    constructor(props,context){
        super(props,context);
        this.context.router;//it works
    }
    btnClick(){
        this.context.router.push("/yourpath");
    }
}
Example.contextTypes={
    router:React.PropTypes.objext
}



安装babel-preset-stage-0依赖后

class Example extends React.Component{
    static contextTypes={
        router:React.PropTypes.object
    }
    constructor(props,context){
        super(props,context);
        this.context.router;
    }
    btnClick(){
        this.context.router.push("/yourpath")
    }
}


同样起作用

注意,调用方法时记得绑定合成事件。例如

<button onClick={this.btnClick.bind(this)}>按钮</button>

注意:router:Object 会报错

应该写成  router:React.PropTypes.object

注意  调用方法时可以使用箭头函数,不需要绑定this

如下:

btnClick=()=>{
    //do something
}



猜你喜欢

转载自blog.csdn.net/qq_35388564/article/details/76169853
今日推荐