React-router路由配置及跳转

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;
``
相关推荐
鹿鹿鹿鹿isNotDefined21 小时前
Antd5.x 在 Next.js14.x 项目中,初次渲染样式丢失
前端·react.js·next.js
叁两1 天前
教你快速从Vue 开发者 → React开发者转变!
前端·vue.js·react.js
吴敬悦1 天前
Claude Code 使用的命令行 UI 库: ink(使用 react 编写命令行界面)
前端·react.js
磊磊磊磊磊1 天前
用AI做了个排版工具,分享一下如何高效省钱地用AI!
前端·后端·react.js
鸡吃丸子1 天前
React Native入门详解
开发语言·前端·javascript·react native·react.js
Hao_Harrision1 天前
50天50个小项目 (React19 + Tailwindcss V4) ✨ | DrinkWater(喝水记录组件)
前端·react.js·typescript·vite7·tailwildcss
前端老宋Running1 天前
别再写 API 路由了:Server Actions 才是全栈 React 的终极形态
前端·react.js·架构
前端老宋Running1 天前
跟“白屏”说拜拜:用 Next.js 把 React 搬到服务器上,Google 爬虫都要喊一声“真香”
前端·react.js·架构
玉宇夕落1 天前
深入理解 React 与 JSX:从组件到 UI 构建
前端·react.js
南山安1 天前
React学习:组件化思想
javascript·react.js·前端框架