使用 router.transitionTo() 不带导航混合的 React Router 1.0
React Router 1.0 using router.transitionTo() without Navigation mixin
有没有更简单的方法从组件访问 Router
对象来执行诸如调用 transitionTo()
之类的操作,而无需使用 Navigation mixin?这是一个 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>
);
}
}
根据 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
};
有没有更简单的方法从组件访问 Router
对象来执行诸如调用 transitionTo()
之类的操作,而无需使用 Navigation mixin?这是一个 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>
);
}
}
根据 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
};