【React-Router】路由快速上手

1. 创建路由开发环境

# 使用CRA创建项目
npm create-react-app react-router-pro

# 安装最新的ReactRouter包
npm i react-router-dom

2. 快速开始

// index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';

const router = createBrowserRouter([
  {
    path: '/login',
    element: 
登录
}, { path: '/article', element:
文章
} ]) const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();

3. 抽象路由模块

【React-Router】路由快速上手_第1张图片

【React-Router】路由快速上手_第2张图片

// @/page/Article/index.js
const Article = () => {
  return <div>文章页</div>
}

export default Article
// @/router/index.js
import Login from '../page/Login'
import Article from '../page/Article'
import { createBrowserRouter } from 'react-router-dom'
const router = createBrowserRouter([
  {
    path: '/login',
    element: <Login></Login>
  },
  {
    path: '/article',
    element: <Article></Article>
  },
  {
    path: '/',
    element: <Login></Login>
  }
])

export default router
// @/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {  RouterProvider } from 'react-router-dom';
// 导入路由
import router from './router';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  
    {/* 路由绑定 */}
    
  
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

你可能感兴趣的:(React-Router,react.js,前端,前端框架)