1.父组件注册路由:
v5版本:
import { Route } from 'react-router-dom'
<Route path="/about" component={About} />
<Route path="/home" component={Home} />
v6版本:
import { Route } from 'react-router-dom'
<Route path="about" element={<About />} />
<Route path="home" element={<Home />} />
2.NavLink点击高亮显示
v5版本:
import { NavLink } from 'react-router-dom'
<NavLink activeClassName="highlight" className="about" to="/about" >About</NavLink>
v6版本:
以下二者选一即可,一定要注意 (isActive ? " highlight") highlight前面的空格!!!
// 官方写法
<NavLink className={({ isActive }) => "about" + (isActive ? " highlight" : "")} to="about">About</NavLink>
// ES6 模版字符串写法
<NavLink className={({ isActive }) => `about ${isActive ? "highlight" : ""}`} to="about">About</NavLink>
3.Switch(单一匹配)更换为Routes
import { Routes,Route } from 'react-router-dom'
<Routes>
<Route path="about" element={<About />} />
<Route path="home" element={<Home />} />
</Routes>
4.Redirect重定向
v5版本:
import { Redirect }from 'react-router-dom'
<Routes>
<Route path="/about" element={<About />} />
<Route path="/home" element={<Home />} />
// 写在这里
<Redirect to="/about" />
</Routes>
v6版本:
import { Navigate }from 'react-router-dom'
<Routes>
<Route path="about/*" element={<About />} />
<Route path="home/*" element={<Home />} />
// 写在这里
<Route path="/*" element={<Navigate to="/about" />} />
</Routes>
5.嵌套路由
v5版本:
// 父组件
<Route path="home/" element={<Home />} />
// 路由链接
<NavLink className="about" to="/home/news" >News</NavLink>
// 注册路由和重定向
<Switch>
<NavLink className="news" to="/home/news" >News</NavLink>
<NavLink className="message" to="/home/message" >Message</NavLink>
<Redirect to="/home/news" />
</Switch>