如何手动更改路由,使用react-router-v4,如<link />这样做,但手动在函数内?

时间:2017-10-23 15:45:53

标签: reactjs react-router-v4

我正在使用 React react-router-v4 开展项目, 我试图找到一种手动触发路线更改的方法。

类似于<Link to="/newpage">组件,它会带您进入新的路线。

但是我想从我的一个方法中手动完成它,

类似于this.router.location = "/newpage"

3 个答案:

答案 0 :(得分:1)

使用this.props.history.push组件或withRouter高阶组件公开的<Link>方法作为上面答案中提到的PompolutZ。

这样的一个例子是<button onClick={() => this.props.history.push('/Home') } />

答案 1 :(得分:0)

使用withRouter高阶组件怎么样?

https://reacttraining.com/react-router/web/api/withRouter

class GoToNewPageButton extends React.Component {
  navigateToNewPage() {
    this.props.history.push('/newpage');
  }

  render() {
    return <button onClick={this.navigateToNewPage.bind(this)}>To the new page!</button>
  }
}

const GoToNewPageWithHistory = withRouter(GoToNewPageButton);

答案 2 :(得分:-1)

渲染一个导航到新位置的重定向组件。

<Redirect to="/somewhere/else"/>

有关详细信息,请查看documentation here.