小编典典

使用React Router以编程方式导航

reactjs

通过使用react-router我可以使用Link元素创建由React Router本机处理的链接。

我在内部看到它的呼唤this.context.transitionTo(...)

我想导航。不是来自链接,而是来自下拉菜单(例如)。如何在代码中执行此操作?什么this.context

我看到了Navigationmixin,但是如果没有,我可以这样做mixins吗?


阅读 614

收藏
2020-07-22

共1个答案

小编典典

带有钩子的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. 使用withRouter高阶组件。
  2. 使用合成并渲染 <Route>
  3. 使用context

React
Router主要是history库的包装器。history通过浏览window.history器和哈希历史记录为您处理与浏览器的交互。它还提供了内存历史记录,这对于没有全局历史记录的环境很有用。这在移动应用程序开发(react- native)和使用Node进行单元测试中特别有用。

一个history实例有用于导航两种方法:pushreplace。如果您将history视为已访问位置的数组,push则将一个新位置添加到该数组中,replace并将该数组中的当前位置替换为新位置。通常,您将push在导航时使用该方法。

在早期版本的阵营路由器,你必须创建自己的history实例,但在第4版的<BrowserRouter><HashRouter><MemoryRouter>组件将创建一个浏览器,哈希和内存的实例为您服务。React
Router history通过router对象下的上下文使与路由器关联的实例的属性和方法可用。

1.使用withRouter高阶成分

withRouter高次成分将注入的history对象作为所述部件的支柱。这样一来,您无需处理即可访问pushreplace方法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>

<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.使用上下文*

但是你可能不应该

最后一个选项是只有在您熟悉使用React的上下文模型时才应使用的选项(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是最简单的实现方法,因此对于大多数用例来说,它们是最好的选择。

2020-07-22