javascript - React Router 1.0 using router.transitionTo() without Navigation mixin - Stack Overflow

Is there an easier way to access the Router object from a ponent to do things like call transitionTo()

Is there an easier way to access the Router object from a ponent to do things like call transitionTo() without using the Navigation mixin? This is an ES6 ponent. Currently on an event like a button click, I have been writing something like this:

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>
    );
  }
}

Is there an easier way to access the Router object from a ponent to do things like call transitionTo() without using the Navigation mixin? This is an ES6 ponent. Currently on an event like a button click, I have been writing something like this:

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>
    );
  }
}
Share Improve this question asked Jul 17, 2015 at 5:45 BradBrad 1,8991 gold badge12 silver badges18 bronze badges 3
  • Confused, why not just this.context.router? – Henrik Andersson Commented Jul 17, 2015 at 5:48
  • 5 Contexts in ES6 is undocumented at the moment. You accept the context in a parameter of the constructor and pass the context to the super. You can then access the context normally. Code examples in this react-router issue. – Mat Gessel Commented Jul 17, 2015 at 6:41
  • Thanks @MatGessel!! I'll document the solution below. – Brad Commented Jul 17, 2015 at 13:37
Add a ment  | 

1 Answer 1

Reset to default 8

Per Mat Gessel's ment, adding the context as a parameter in the constructor will give you access to the router.

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
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745141943a4613471.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信