有没有更简单的方法来访问Router
组件中的对象执行诸如调用之类的操作transitionTo()
不使用导航混合?这是一个 ES6 组件。目前,在像按钮单击这样的事件上,我一直在写这样的内容:
class Button extends React.Component {
handleClick(e) {
e.preventDefault();
var router = this._reactInternalInstance._context.router;
router.transitionTo('/search');
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>
{this.props.children}
</button>
);
}
}
Per 马特·格塞尔 https://stackoverflow.com/users/199296/mat-gessel的注释,在构造函数中添加上下文作为参数将使您能够访问路由器。
class Button extends React.Component {
constructor(props, context) {
super(props, context);
this.context = context;
}
handleClick(e) {
e.preventDefault();
this.context.router.transitionTo('/search');
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
router: React.PropTypes.object.isRequired
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)