我们使用 react脚手架create-react-app 来构建 react 项目;
一、安装 npm install -g create-react-app
二、创建react应用
create-react-app是全局命令来创建react项目
create-react-app 项目名称
创建成功后
今天我们主要看看 路由及路由嵌套
我们新建一个router.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/** * Created by PhpStorm. * User: iyahe@qq.com (天明) * Date: 2019/6/11 0011 * Time: 下午 16:55 * Description: */ import React from 'react'; import {HashRouter, Route, Switch} from 'react-router-dom'; import Home from './views/home'; import Detail from './views/detail'; import Index from './views/index' const BasicRoute = () => ( <HashRouter> <Switch> <Route exact path="/" component = {Index} /> <Route path="/home" component = {Home} /> <Route exact path="/detail/:id" component = {Detail} /> </Switch> </HashRouter> ); export default BasicRoute; |
路由嵌套, 我们主要给Home路由嵌套子页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/** * Created by PhpStorm. * User: iyahe@qq.com (天明) * Date: 2019/6/11 0011 * Time: 下午 16:54 * Description: */ import React from 'react'; import { Route } from 'react-router-dom'; export const DetailsDef = (props) => { return ( <div> 我在 home/abc/def 里 </div> ) } export const Details = (props) => { return ( <div> <p>详情内容子路由</p> <a href='#/home/abc/def'>去->home/abc/def</a> </div> ) } export default class Home extends React.Component { render() { return ( <div> <a href='#/detail/30'>去detail</a> <button onClick={() => this.props.history.push({ pathname: '/detail', state: { id: 3 } })}>通过函数跳转</button> <br/> <a href='#/home/abc'>去home的子路由里面</a> <div className="ids"> <Route path="/home/abc" component={Details}></Route> <Route path="/home/abc/def" component={DetailsDef}></Route> </div> </div> ) } } |
这样, 我们访问到: #/home/abc 时候, 加载 omponent={Details} 组件
访问到: home/abc/def, 加载 component={DetailsDef} 组件