包含了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
版权声明:本文为susuzhe123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。