React-router:如何手动调用链接?

JavaScript

Gil启人

2020-03-12

我是ReactJS和React-Router的新手。我有一个组件,通过props <Link/>react-router接收一个对象每当用户单击该组件内部的“下一步”按钮时,我都想<Link/>手动调用对象。

现在,我正在使用refs访问支持实例,并手动单击<Link/>生成的'a'标记

问题:有没有办法手动调用链接(例如this.props.next.go)?

这是我目前的代码:

//in MasterPage.js
var sampleLink = <Link to="/sample">Go To Sample</Link>
<Document next={sampleLink} />

//in Document.js
...
var Document = React.createClass({
   _onClickNext: function() {
      var next = this.refs.next.getDOMNode();
      next.querySelectorAll('a').item(0).click(); //this sounds like hack to me
   },
   render: function() {
      return (
         ...
         <div ref="next">{this.props.next} <img src="rightArrow.png" onClick={this._onClickNext}/></div>
         ...
      );
   }
});
...

这是我想要的代码:

//in MasterPage.js
var sampleLink = <Link to="/sample">Go To Sample</Link>
<Document next={sampleLink} />

//in Document.js
...
var Document = React.createClass({
   render: function() {
      return (
         ...
         <div onClick={this.props.next.go}>{this.props.next.label} <img src="rightArrow.png" /> </div>
         ...
      );
   }
});
...

第912篇《React-router:如何手动调用链接?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
小宇宙猪猪乐 2020.03.12

5.x版中,您可以使用以下useHistory钩子react-router-dom

// Sample extracted from https://reacttraining.com/react-router/core/api/Hooks/usehistory
import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
阿飞Pro 2020.03.12

反应路由器4

您可以通过v4中的上下文轻松调用push方法:

this.context.router.push(this.props.exitPath);

上下文在哪里:

static contextTypes = {
    router: React.PropTypes.object,
};
蛋蛋猿 2020.03.12

https://github.com/rackt/react-router/blob/bf89168acb30b6dc9b0244360bcbac5081cf6b38/examples/transitions/app.js#L50

或者您甚至可以尝试执行onClick这个(更暴力的解决方案):

window.location.assign("/sample");

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android