加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 在React-Router v4中以编程方式导航

发布时间:2020-12-15 20:55:14 所属栏目:百科 来源:网络整理
导读:我等不及了,我开始使用最新的alpha版本的react-router v4。全新的 BrowserRouter /非常适合保持您的UI与浏览器历史记录同步,但如何使用它以编程方式导航? 路由器会将历史对象推送到props散列中的组件。所以在你的组件中,只需: this.props.history.push(
我等不及了,我开始使用最新的alpha版本的react-router v4。全新的< BrowserRouter />非常适合保持您的UI与浏览器历史记录同步,但如何使用它以编程方式导航?
路由器会将历史对象推送到props散列中的组件。所以在你的组件中,只需:

this.props.history.push( ‘/ mypath中’)

这是一个完整的例子:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读