安装react-router-dom
npm install react-router-dom
修改app.tsx组件
import React, { useState } from "react";
import {
BrowserRouter,
Route,
Link,
Routes
} from "react-router-dom"
interface IProps {
title: string
}
const About = () => {
return <div>about</div>
}
const Users = () => {
return <div>users</div>
}
const Home = () => {
return <div>home</div>
}
const App = (props: IProps) => {
const { title } = props;
const [collapsed, setCollapsed] = useState(false);
return (
<BrowserRouter>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/users">Users</Link></li>
</ul>
<Routes>
<Route path="/about" element={<About />}>
</Route>
<Route path="/users" element={<Users />}>
</Route>
<Route path="/" element={<Home />}>
</Route>
</Routes>
</BrowserRouter>
)
};
export default App;
页面效果
安装antd使用样式
npm install antd
修改app.tsx组件
import React, { useState } from "react";
import {
BrowserRouter,
Route,
Link,
Routes
} from "react-router-dom"
import { Layout, Menu } from "antd";
import {
HomeOutlined,
ShopOutlined,
UserOutlined
} from '@ant-design/icons';
import 'antd/dist/antd.css';
const { Sider, Content } = Layout;
interface IProps {
title: string
}
const About = () => {
return <div>about</div>
}
const Users = () => {
return <div>users</div>
}
const Home = () => {
return <div>home</div>
}
const App = (props: IProps) => {
const { title } = props;
const [collapsed, setCollapsed] = useState(false);
return (
<BrowserRouter>
<Layout>
<Sider trigger={null} collapsible collapsed={collapsed}>
<Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
<Menu.Item key="1" icon={<HomeOutlined />}>
<Link to="/">Home</Link>
</Menu.Item>
<Menu.Item key="2" icon={<ShopOutlined />}>
<Link to="/about">About</Link>
</Menu.Item>
<Menu.Item key="3" icon={<UserOutlined />}>
<Link to="/users">Users</Link>
</Menu.Item>
</Menu>
</Sider>
<Layout className="site-layout">
<Content>
<Routes>
<Route path="/about" element={<About />}>
</Route>
<Route path="/users" element={<Users />}>
</Route>
<Route path="/" element={<Home />}>
</Route>
</Routes>
</Content>
</Layout>
</Layout>
</BrowserRouter>
)
};
export default App;
因为引用了antd.css样式文件,所以需要安装style-loader和css-loader
npm install --save-dev style-loader css-loader
修改webpack.config.js文件增加以下配置
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
页面效果
这里使用的BrowserRouter在非首页刷新会出现错误 Cannot GET /xxx,此时可以在webpack.config.js文件中的devServer对象中增加 historyApiFallback:true配置信息,也可以使用HashRouter。区别就是HashRouter在url中会出现 “#”号,比如: http://localhost:8080/#/about
package.json依赖
"react-router-dom": "^6.2.1",
"antd": "^4.18.8",
"css-loader": "^6.6.0",
"style-loader": "^3.3.1",
|