目前使用的版本
"react-router-dom": "^5.1.2",
先定義頁面
Topic.js, About.js, Topic.js, A.js, B.js (將里面的文字做相應的替換)
import React from 'react'
export default class Topic extends React.Component {
render() {
return (
<>
<div>
Topic頁面
</div>
</>
)
}
}
Home2.js
import React from 'react'
import { Link } from 'react-router-dom'
export default class Home extends React.Component {
render() {
return (
<div>
<ul>
<li>
<Link to="/">Home2</Link>
</li>
<li>
<Link to="/about">About2</Link>
</li>
<li>
<Link to="/topic">Topics2</Link>
</li>
</ul>
<hr/>
{/* 子頁面 */}
{/* 所有子組件 */}
{this.props.children}
</div>
)
}
}
router.js
import React from 'react'
import { HashRouter as Router, Route, Link, Switch, useRouteMatch, useParams } from 'react-router-dom'
import Main from './Main'
import About from './About'
import Topic from './Topic'
import Home from './Home'
import A from './A'
import B from './B'
/**
* 這個頁面就是 最終輸出頁面
* 在項目根目錄的 index.js 文件里面
*
* import Router from './pages/router_demo/router02/router';
* ReactDOM.render(<Router />, document.getElementById('root'));
*/
export default class IRouter extends React.Component {
render() {
return (
<>
<Router>
{/* 只能有一個根節(jié)點 */}
<Home>
{/* 頁面路由,一個 Route 代表一個頁面 */}
{/* 4.0 版本開始允許加載多個路由咏闪,所以建議加上 exact 進行精準匹配*/}
<Route exact={true} path="/" component={Main}/>
<Route exact={true} path="/about" component={About}/>
<Route exact={true} path="/topic" component={Topic}/>
{/* 嵌套路由秕衙,不能在父級家 exact完丽,因為先要匹配父級然后才能匹配子集 */}
{/* 比如:/nested/a , 會先匹配父級 /nested 飯后才能匹配 /nested/a */}
<Route path="/nested" component={() => <Nested />} />
</Home>
</Router>
</>
)
}
}
/**
* 函數組件
* @param {*} props
*/
export function Nested(props) {
// 獲取route的匹配數據
// path 路徑, url 路徑, params 參數
const { path, url, params } = useRouteMatch()
// 獲取 path 參數, http://localhost:3000/a/:number
// const { number } = useParams()
console.log(path, url, params)
return (
<>
<ul>
<li>
<Link to={`${path}/a`}>A頁面</Link>
</li>
<li>
<Link to={`${path}/b`}>B頁面</Link>
</li>
</ul>
<hr/>
{/* {props.children} */}
<Switch>
<Route exact path={path} component={() => <h3>嵌套路由</h3>}/>
<Route path={`${path}/a`} component={A}/>
<Route path={`${path}/b`} component={B}/>
</Switch>
</>
)
}
嵌套路由的重點在于烤送,嵌套路由歼指,不能在父級加 exact
(精準匹配),因為先要匹配 父級 然后才能匹配 子集
比如:/nested/a
评姨, 會先匹配父級 /nested
后才能匹配 /nested/a
<Route path="/nested" component={() => <Nested />} />
....... 分隔符 ...........
// <Nested /> 組件的內部
// 這里的 path 就是 /nested
// `${path}/a` 就是 /nested/a
<Switch>
<Route exact path={path} component={() => <h3>嵌套路由</h3>}/>
<Route path={`${path}/a`} component={A}/>
<Route path={`${path}/b`} component={B}/>
</Switch>