包含了LInk跳轉以及js觸發跳轉並傳參。
這是項目的目錄結構,主要的代碼都在src目錄下,src下面建立一個containers檔案夾放我們的一些組件,router檔案夾是配置路由用的。
按照順序來寫:detail檔案夾下的代碼
import React from 'react'class Detail extends React.Component { render() { return ( <p>Detail,url參數:{this.props.params.id}</p> ) }}export default Detail
home:
import React from 'react'import { Link } from 'react-router'class Home extends React.Component { render() { return ( <div> <p>Home</p> <Link to="/list">to list</Link> </div> ) }}export default Home
list:
import React from 'react'import { hashHistory } from 'react-router'class List extends React.Component { render() { const arr = [1, 2, 3] return ( <ul> {arr.map((item, index) => { return <li key={index} onClick={this.clickHandler.bind(this, item)}>js jump to {item}</li> })} </ul> ) } clickHandler(value) { hashHistory.push('/detail/' + value) }}export default List
404yemian:
import React from 'react'class NotFound extends React.Component { render() { return ( <p>404 NotFound</p> ) }}export default NotFound
在containers下面有一個app.jsx總入口檔案:
import React from 'react'class App extends React.Component { render() { return ( <div>{this.props.children}</div> ) }}export default App
router檔案夾下的:
import React from 'react'import { Router, Route, IndexRoute } from 'react-router'import App from '../containers/App'import Home from '../containers/Home'import List from '../containers/List'import Detail from '../containers/Detail'import NotFound from '../containers/NotFound'class RouteMap extends React.Component { updateHandle() { console.log('每次router變化之後都會觸發') } render() { return ( <Router history={this.props.history} onUpdate={this.updateHandle.bind(this)}> <Route path='/' component={App}> <IndexRoute component={Home}/> <Route path='list' component={List}/> <Route path='detail/:id' component={Detail}/> <Route path="*" component={NotFound}/> </Route> </Router> ) }}export default RouteMap
最終最外層的index.js:
import React from 'react'import { render } from 'react-dom'import { hashHistory } from 'react-router'import RouteMap from './src/router/routeMap'render( <RouteMap history={hashHistory}/>, document.getElementById('App'))
使用的router版本是^2.8.1,如果下載的是4.0以上的版本,那麼寫法就和現在的幾乎是完全不一樣,他做了很大的改動,配置的時候注意router的版本號碼。
項目地址https://github.com/wineSu/myReact/tree/master/src/containers