鍍金池/ 問(wèn)答/HTML5  HTML/ 如何在react-router4.2中使用js 路由跳轉(zhuǎn)?

如何在react-router4.2中使用js 路由跳轉(zhuǎn)?

1.頁(yè)面有有個(gè)按鈕 ,點(diǎn)擊這個(gè)按鈕跳轉(zhuǎn)頁(yè)面

官方文檔說(shuō):使用withRouter解決

=====================
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

class ShowTheLocation extends React.Component {
static propTypes = {

match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired

}

render() {

const { match, location, history } = this.props

return (
  <div>You are now at {location.pathname}</div>
)

}
}

const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

=====================
在實(shí)際應(yīng)用的時(shí)候 這段代碼怎么用呢?
withRouter 是一個(gè)高階組件? 返回一個(gè)ShowTheLocationWithRouter函數(shù)? 那這個(gè)函數(shù)怎么用到跳轉(zhuǎn)呢?

const { match, location, history } = this.props // 這行是什么意思呢?

使用 history.push('/xxx') 這樣嗎

現(xiàn)在有一個(gè)button 組件 怎么在這個(gè)組件上添加事件進(jìn)行路由跳轉(zhuǎn)呢

回答
編輯回答
孤巷

拿到history后就可以用代碼進(jìn)行跳轉(zhuǎn)了,ReactTraining/history: Manage session history with JavaScript這是history的倉(cāng)庫(kù),相關(guān)方法查看這個(gè)的文檔

2017年3月15日 14:00
編輯回答
浪蕩不羈

// history.js
import createHistory from 'history/createBrowserHistory'
export default createHistory()

import history from 'history'
history.push(path)
2017年11月2日 08:30