参考资料
中文->http://www.reactrouter.cn/docs/getting-started/tutorial
英文->https://reactrouter.com/en/6.6.2
首页包裹路由
import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from './App'
ReactDOM.render(
<BrowserRouter>
{/* The rest of your app goes here */}
<App />
</BrowserRouter>
);
嵌套路由
import { Routes, Route } from "react-router-dom";
import News from 'page/hihi/news'
import Tools from 'page/hihi/tools'
const App = () => {
return(
<div>
路由:
<Routes>
<Route path="hihi/news" element={<News />} />
<Route path="hihi/tools" element={<Tools />} />
<Route
path="*"
element={
<>404</>
}
/>
</Routes>
</div>
)
}
export default App
NavLink和Link
import React from 'react';
import { NavLink, Link } from "react-router-dom";
const layOutRoutes = () => {
return (
<>
<NavLink to="/hihi/news">新闻</NavLink>
<NavLink to="/hihi/tools">工具</NavLink>
<Link to="/hihi/news">新闻</Link>
<Link to="/hihi/tools">工具</Link>
</>
)
}
export default React.memo(layOutRoutes);
发现Navlink随着路由变化会自带active类,而Link没有
可以通过isActive来给样式高亮
<NavLink className={({ isActive }) => isActive ? "red" : "blue"} to="/hihi/news">新闻</NavLink>
<NavLink className={({ isActive }) => isActive ? "red" : "blue"} to="/hihi/tools">工具</NavLink>
注:虽然可以改变URL,但整个页面不会重新加载