1、安装依赖react-router-dom
npm install react-router-dom -S
2、创建文件配置router.jsx
import { Route } from 'react-router-dom';
import Login from '@views/login/Index.jsx';
import Settings from '@views/settings/Index.jsx';
// 定义路由配置数组
const routes = [
{
path: '/',
exact:true,
component: Login,
},
{
path: '/login',
component: Login,
},
{
path: '/settings',
component: Settings,
},
];
// 将路由配置数组转换为Route组件(注意:Component属性是大写开头)
const renderRoutes = () => routes.map((route, index) => (
<Route
key={index}
path={route.path}
Component={route.component}
exact ={route.exact}
/>
));
export default renderRoutes;
3、在APP.jsx文件中引入并使用
import renderRoutes from '@router/index.jsx';
import{HashRouter, Routes,Route,Router}from"react-router-dom";
function App() {
return (
<div>
<HashRouter>
<Routes>
{renderRoutes()}
</Routes>
</HashRouter>
</div>
)
}
export default App;
如果不单独配置router.jsx的话,也可以在APP.jsx中直接写
import Login from './views/login/Index.jsx';
import Settings from './views/settings/Index.jsx';
import{HashRouter, Routes,Route,Router}from"react-router-dom"
function App() {
return (
<div>
<HashRouter>
<Routes>
<Route path="/" Component={Login}></Route>
<Route path="/settings" Component={Settings}></Route>
</Routes>
</HashRouter>
</div>
)
}
export default App;
4、路由跳转
举例:在登录页面,点击
import { useNavigate } from "react-router-dom";
const Login = () => {
const Navigate = useNavigate();
const goSettings = () => {
Navigate('/settings');
};
return (
<div>
<button onClick={goSettings}>跳转到设置页面</button>
</div>
)
};
export default Login;
``