标签:用法 地方 ops element doc 修改 关于 efault reg
第一步:引包两个
命令:cnpm i -S react-router react-router-dom
第二步:用路由管理APP页面
1.创建主路由管理页面,在这里使用了路由嵌套
1 import React, { Component } from ‘react‘; 2 import { Route, BrowserRouter } from ‘react-router-dom‘ 3 import App from ‘../App‘ 4 import SubRouter from ‘./SubRouter‘ //二级路由 5 6 export default class ReactApp extends Component { 7 render() { 8 return ( 9 <BrowserRouter> 10 <App> 11 {/* 这里为了分离得彻底,使用组件嵌套,app组件跳到SubRouter组件*/} 12 <Route path="/" component={SubRouter}></Route> 13 </App> 14 </BrowserRouter> 15 ) 16 } 17 }
2.创建二级路由页面,引入组件
1 import React, { Component } from ‘react‘ 2 import { Route, Switch } from ‘react-router-dom‘ 3 import Home from ‘../Component/Home‘ 4 import Movie from ‘../Component/Movie‘ 5 import About from ‘../Component/About‘ 6 7 export default class SubRouter extends Component { 8 render() { 9 return ( 10 // 路由配置 11 <Switch> 12 <Route exact path="/" component={Home}></Route> 13 <Route exact path=‘/movie‘ component={Movie}></Route> 14 <Route exact path="/about" component={About}></Route> 15 </Switch> 16 ) 17 } 18 }
3.在App页面给显示位置,以及设置点击跳转
1 import React, { Component } from ‘react‘; 2 import { Link } from ‘react-router-dom‘ 3 export default class App extends Component { 4 render() { 5 return ( 6 <div> 7 {/* 点击路由跳转,使用react-router-dom的Link */} 8 <ul> 9 <li> 10 <Link to=‘/‘>首页</Link > 11 </li> 12 <li> 13 <Link to=‘/movie‘>电影</Link > 14 </li> 15 <li> 16 <Link to=‘/about‘>关于</Link > 17 </li> 18 </ul> 19 20 {/* 在APP主页面,给SubRouter留显示位置*/} 21 {this.props.children} 22 </div> 23 ) 24 } 25 }
4.修改index.js需要渲染的组件,由渲染原来的APP改为渲染主路由,因为已经用路由管理App页面了
1 import React from ‘react‘; 2 import ReactDOM from ‘react-dom‘; 3 import AppRouter from ‘./AppRouter/AppRouter‘; 4 import * as serviceWorker from ‘./serviceWorker‘; 5 6 ReactDOM.render(<AppRouter />, document.getElementById(‘root‘)); 7 serviceWorker.unregister();
三.页面效果
四.文件目录
写得有什么不对的地方,还请大家多多指教,多谢。
标签:用法 地方 ops element doc 修改 关于 efault reg
原文地址:https://www.cnblogs.com/dmyxs/p/12183022.html