您的位置:首页 > Web前端 > React

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

2017-07-27 09:42 447 查看
示例:

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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: