1.新建react项目 安装react-router-dom插件
create-react-app 项目名
npm install react-router-dom
2.基础代码
import React from 'react'; import {BrowserRouter as Router, Route,Link} from 'react-router-dom' import Index from './pages/index' import List from './pages/list' import Video from './pages/video' import './index.css' function ReactRouter(){ return( <Router> <div className='mainDiv'> <div className='leftNav'> <h3>一级导航</h3> <ul> <li><Link to='/'>首页</Link></li> <li><Link to='/pages/list/'>列表</Link></li> <li><Link to='/pages/video/'>视频</Link></li> </ul> </div> <div className="rightMain"> <Route path="/" exact component={Index}/> <Route path="/pages/list/" component={List}/> <Route path="/pages/video/" component={Video}/> </div> </div> </Router> ) } export default ReactRouter
3.三个子页面代码
//List import React from 'react'; import { Link, Route} from 'react-router-dom' import Goods from './list/goods' import Tasks from './list/tasks' function List(){ return( <div> <div className="topNav"> <ul> <li><Link to='/pages/list/goods'>商品列表</Link></li> <li><Link to='/pages/list/tasks'>任务列表</Link></li> </ul> </div> <Route path='/pages/list/' exact component={Goods}/> <Route path='/pages/list/goods' component={Goods}/> <Route path='/pages/list/tasks' component={Tasks}/> </div> ) } export default List //Index import React from 'react'; function Index(){ return( <div>Index页面</div> ) } export default Index //Video import React from 'react'; function Video(){ return( <div>video页面</div> ) } export default Video
4.list子页面代码
//Goods import React from 'react'; function Goods(){ return( <div>Goods页面</div> ) } export default Goods //Tasks import React from 'react'; function Tasks(){ return( <div>Tasks页面</div> ) } export default Tasks