目录
一、安装react-router-dom
npm install react-router-dom
安装完成后在package.json文件中进行查看:
二、创建路由文件和页面文件
三、写入对应文件代码
// router.js
import Home from "../pages/home/index";
import Login from "../pages/login/index";
import NotFound from "../pages/notFound/index";
const routers = [
{
path: '/Home',
name: '主页面',
components: Home
},
{
path: '/Login',
name: '登录页',
components: Login
},
{
path: '/NotFound',
name: '404',
components: NotFound
}
]
export default routers;
// home.js
import React from 'react';
import './index.css';
function Home() {
return (
<div className='Home Home-pagination'>主页面</div>
)
}
export default Home;
// login.js
import React from 'react';
import './index.css';
function Login() {
return (
<div className='Home Home-pagination'>登录页面</div>
)
}
export default Login;
// 404
import React from 'react';
import './index.css';
function NotFound() {
return (
<div className='Home Home-pagination'>404</div>
)
}
export default NotFound;
四、修改入口index.js
// 引入react-router-dom的BrwoserRouter用来包住App整个页面
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
reportWebVitals();
五、修改App.js,插入路由
import './App.css';
import routers from './router';
import { Routes, Link, Route } from 'react-router-dom';
function App() {
return (
<div className="App App-header">
<div className="App App-router">
{
routers.map((item, index) => (
<Link className="App App-link" to={item.path} key={index}> {item.name} </Link>
))
}
</div>
<Routes className="App App-content">
{
routers.map((item, index) => (
<Route path={item.path} key={index} element={<item.components />}></Route>
))
}
</Routes>
</div >
);
}
export default App;