基本的 嵌套路由组件,直接在代码中,引入即可,
1 // 嵌套路由 2 import React from 'react'; 3 import BackHome from '../component/BackHome'; // 返回首页组件 4 import { BrowserRouter as Router, Switch, Route, Link,useRouteMatch, useParams } from "react-router-dom"; 5 /* 6 useRouteMatch, useParams 为新版Hooks新增项 7 */ 8 const Topics = () => { 9 let match = useRouteMatch(); 10 return( 11 <div> 12 <BackHome/> 13 <div> 14 <h2>Nested Routing</h2> 15 {/* 所有内容均需放进 <Router>内 */} 16 <Router> 17 {/* 嵌套路由按钮 */} 18 <ul> 19 <li> 20 <Link to={`${match.url}/components`}> 21 Components 22 </Link> 23 </li> 24 <li> 25 <Link to={`${match.url}/props-v-state`}> 26 Props v. State 27 </Link> 28 </li> 29 </ul> 30 31 {/* 嵌套路由内容 */} 32 <Switch> 33 <Route path={`${match.path}/:topicId`}> 34 <Topic /> 35 </Route> 36 <Route path={match.path}> 37 <h3>Please select a topic.</h3> 38 </Route> 39 </Switch> 40 </Router> 41 </div> 42 </div> 43 ) 44 } 45 46 function Topic() { 47 let { topicId } = useParams(); 48 return <h3>Requested Routing ID: {topicId}</h3>; 49 } 50 51 export default Topics;
后续会单独总结 react-router-dom 及 Hooks