使用 React 路由器以编程方式导航

2024-02-08

With react-router我可以使用Link元素来创建由反应路由器本机处理的链接。

我看到它内部调用this.context.transitionTo(...).

我想做一个导航。不是来自链接,而是来自下拉选择(作为示例)。我怎样才能在代码中做到这一点?什么是this.context?

我看到了Navigationmixin,但是我可以在不这样做的情况下做到这一点吗mixins?


更新:2022 年:使用 useNavigate 反应 Router v6.6.1

The useHistory()hook 现已弃用。如果您使用的是 React Router 6,以编程方式导航的正确方法如下:

import { useNavigate } from "react-router-dom";

function HomeButton() {
  const navigate = useNavigate();

  function handleClick() {
    navigate("/home");
  }

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

带钩子的 React Router v5.1.0

有一个新的useHistory如果您使用 React >16.8.0 和功能组件,请在 React Router >5.1.0 中挂钩。

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

反应路由器 v4

使用 React Router v4,您可以采用三种方法在组件内进行编程路由。

  1. Use the withRouter高阶分量。
  2. 使用合成并渲染<Route>
  3. Use the context.

React Router 主要是一个包装器history https://github.com/ReactTraining/history图书馆。history处理与浏览器的交互window.history https://developer.mozilla.org/en-US/docs/Web/API/Window/history为您提供浏览器和哈希历史记录。它还提供内存历史记录,这对于没有全局历史记录的环境非常有用。这在移动应用程序开发中特别有用(react-native)并使用 Node.js 进行单元测试。

A history实例有两种导航方法:push and replace。如果你想到history作为访问过的位置的数组,push将向数组添加一个新位置并且replace将用新位置替换数组中的当前位置。通常您会想要使用push导航时的方法。

在 React Router 的早期版本中,您必须创建自己的history实例,但在 v4 中<BrowserRouter>, <HashRouter>, and <MemoryRouter>组件将为您创建浏览器、哈希和内存实例。 React Router 使得属性和方法history与您的路由器关联的实例可通过上下文在router object.

1. 使用withRouter高阶分量

The withRouter高阶组件将注入history对象作为组件的支柱。这允许您访问push and replace方法,而无需处理context.

import { withRouter } from 'react-router-dom'
// this also works with react-router-native

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

2. 使用合成并渲染<Route>

The <Route>组件不仅仅用于匹配位置。您可以渲染无路径路线并它将始终与当前位置匹配. The <Route>组件传递相同的 propswithRouter,这样您就可以访问history方法通过history prop.

import { Route } from 'react-router-dom'

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

3. 使用上下文*

但你可能不应该

最后一个选项只有在您觉得使用 React 很舒服时才应该使用context https://facebook.github.io/react/docs/context.html模型(React 的 Context API 从 v16 开始稳定)。

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

// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}

1 和 2 是最简单的实施选择,因此对于大多数用例来说,它们是您的最佳选择。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 React 路由器以编程方式导航 的相关文章

随机推荐