这是项目的目录结构,主要的代码都在src目录下,src下面新建一个containers文件夹放我们的一些组件,router文件夹是配置路由用的。
import React from 'react' class Detail extends React.Component { render() { return ( <p>Detail,url参数:{this.props.params.id}</p> ) } } export default Detailhome:
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 Homelist:
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 List404yemian:
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 Approuter文件夹下的:
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 原文链接:https://www.f2er.com/react/303282.html