通过react-router
,我可以使用Link
元素来创建由react router native 处理的链接。
我看到它在内部调用 this.context.transitionTo(...)
。
我想做一个导航。不是来自链接,而是来自下拉选择(作为示例)。我怎样才能在代码中做到这一点? this.context
是什么?
我看到了 Navigation
mixin,但是我可以在没有 mixins
的情况下执行此操作吗?
最佳答案
UPDATE: 2022: React Router v6.6.1 with useNavigate
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 with hooks
有一个新的useHistory
如果您使用 React >16.8.0 和功能组件,请在 React Router >5.1.0 中 Hook 。
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
.
React Router 主要是 history
的包装器图书馆。 history
处理与浏览器的 window.history
的交互为您提供浏览器和哈希历史记录。它还提供内存历史记录,这对于没有全局历史记录的环境非常有用。这在移动应用程序开发 ( react-native
) 和使用 Node 进行单元测试时特别有用。
一个history
实例有两种导航方法:push
和replace
。如果您想到history
作为访问过的位置的数组,push
将向数组添加一个新位置和 replace
将用新位置替换数组中的当前位置。通常您会想要使用push
导航时的方法。
在早期版本的 React Router 中,您必须创建自己的 history
实例,但在 v4 中 <BrowserRouter>
, <HashRouter>
,和<MemoryRouter>
组件将为您创建浏览器、哈希和内存实例。 React Router 使得 history
的属性和方法与您的路由器关联的实例可通过上下文在 router
下获取对象。
1。使用withRouter
高阶组件
withRouter
高阶组件将注入(inject) history
对象作为组件的支柱。这允许您访问 push
和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>
<Route>
组件不仅仅用于匹配位置。您可以渲染无路径路线,并且它将始终与当前位置匹配。 <Route>
组件传递与 withRouter
相同的 props ,这样您就可以访问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 感到舒服时才应该使用。模型(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 是最容易实现的选择,因此对于大多数用例来说,它们是您的最佳选择。
关于javascript - 使用 React 路由器以编程方式导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31079081/