发布于 3年前

React Router 5.1.0使用useHistory做页面跳转导航

从React Router v5.1.0开始,新增了useHistory钩子(hook),如果是使用React >16.8.0,编写以下函数组件,使用useHistory即可实现编程时页面跳转导航。

示例:

import { useHistory } from "react-router-dom";
function HomeButton() {
  const history = useHistory();
  function handleClick() {
    history.push("/home");
  }
  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

React Router v4编程式页面跳转的方式(补充)

如果是React Router v4,可以使用以下方法:

  • 使用withRouter组件
  • 使用<Route>标签
  • 使用context

1、使用withRouter组件

withRouter组件将注入history对象作为该组件的属性。这样,不需要处理context,可直接访问push和replace方法。

示例:

import { withRouter } from 'react-router-dom'
const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
))

2、使用<Route>标签

<Route>组件不仅用于匹配位置。 您可以渲染无路径的路由,它始终与当前位置匹配。 <Route>组件传递与withRouter相同的属性,因此能够通过history的属性访问history的方法。

import { Route } from 'react-router-dom'
const Button = () => (
  <Route render={({ history}) => (
    <button
      type='button'
      onClick={() => { history.push('/new-location') }}
    >
      Click Me!
    </button>
  )} />
)

3、使用context

这个方法不推荐,context api不是很稳定。示例如下:

const Button = (props, context) => (
  <button
    type='button'
    onClick={() => {
      context.history.push('/new-location')
    }}
  >
    Click Me!
  </button>
)

Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}

推荐使用方法1和2,实现起来也简单。

©2020 edoou.com   京ICP备16001874号-3