自学内容网 自学内容网

React-router路由配置及跳转

1、V6对比V5的修改内容

1、API: useNavigate 代替了useHistory
2、废弃了Route组件的exact属性。
3、组件 <Routes>代替了<Switch>
4、组件NavLink中移除了 activeStyle activeClassName 属性。

2、安装依赖react-router-dom

npm install react-router-dom -S

3、创建文件配置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: '/',
    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}
  />
));

export default renderRoutes;

4、在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;

5、路由跳转

举例:在登录页面,点击

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;

注意

1、Route组件的常用属性有以下:
path:与URL匹配的路径
children:嵌套的路由配置
element/Component: 元素/组件
lazy:返回一个动态的组件引入。
2、Route中没有属性name


原文地址:https://blog.csdn.net/qq_39460057/article/details/140668298

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!