在 React-Router v4 中以编程方式导航 [英] Navigating Programmatically in React-Router v4
本文介绍了在 React-Router v4 中以编程方式导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我迫不及待地开始使用 react-router
v4 的最新 alpha 版本.全新的 <BrowserRouter/>
非常适合让您的 UI 与浏览器历史记录保持同步,但是我如何使用它以编程方式进行导航?
解决方案
路由器将在 props
散列中向您的组件添加一个 history
对象.因此,在您的组件中,只需执行以下操作:
this.props.history.push('/mypath')
这是一个完整的例子:
在 App.js
中:
从'react'导入React从react-router-dom"导入 {BrowserRouter 作为路由器,路由}从'./Login'导入登录导出默认类 App 扩展 React.Component {使成为() {返回 (<路由器><div><路由精确路径='/login' component={Login}/>
</路由器>)}}
在 Login.js
中:
import React, {PropTypes} from 'react'导出默认类登录扩展 React.Component {构造函数(道具){超级(道具)this.handleLogin = this.handleLogin.bind(this)}句柄登录(事件){event.preventDefault()//在这里做一些登录逻辑,如果成功:this.props.history.push(`/mypath`)}使成为() {返回 (<div><form onSubmit={this.handleLogin}><input type='submit' value='登录'/></表单>
)}}
I couldn't wait and I jumped into using the latest alpha version of react-router
v4. The all-new <BrowserRouter/>
is great in keeping your UI in sync with the browser history, but how do I use it to navigate programmatically?
解决方案
The router will add a history
object to your component in the props
hash. So in your component, simply do:
this.props.history.push('/mypath')
Here is a full example:
In App.js
:
import React from 'react'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import Login from './Login'
export default class App extends React.Component {
render() {
return (
<Router>
<div>
<Route exact path='/login' component={Login} />
</div>
</Router>
)
}
}
In Login.js
:
import React, {PropTypes} from 'react'
export default class Login extends React.Component {
constructor(props) {
super(props)
this.handleLogin = this.handleLogin.bind(this)
}
handleLogin(event) {
event.preventDefault()
// do some login logic here, and if successful:
this.props.history.push(`/mypath`)
}
render() {
return (
<div>
<form onSubmit={this.handleLogin}>
<input type='submit' value='Login' />
</form>
</div>
)
}
}
这篇关于在 React-Router v4 中以编程方式导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文