Ant Design of React 学习笔记(2)
Ant Design of React组件引用及路由跳转,接着笔记(1)继续
这里我们主要3点:1.使用Ant的组件;2,如何引用页面组件;3,路由导航跳转
这是我的目录结构
公共组件目录定义了公共组件header,和底部公共组件footer
一,Ant组件的引用
在头部header里面引用Ant的导航菜单,代码:
import React from "react";
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import {useState} from "react";
import {Link, useLocation} from "react-router-dom";
const items: MenuProps['items'] = [
{
label: <Link to={'/'}>Home</Link>,
key: '/',
},
{
label: <Link to={'/product'}>Product</Link>,
key: '/product',
},
{
label: <Link to={'/about'}>About</Link>,
key: '/about',
}
];
const App: React.FC = () => {
const location=useLocation()
const [, setCurrent] = useState(location.pathname);
const onClick: MenuProps['onClick'] = (e) => {
//console.log('click ', e);
setCurrent(e.key);
};
return <Menu onClick={onClick} selectedKeys={[location.pathname]} mode="horizontal" items={items}/>;
};
export default App;
二,页面组件的引用及导航路由跳转
先对index.tsx入口文件进行处理,代码如下:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter, Route, Routes} from 'react-router-dom';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<BrowserRouter>
<React.StrictMode>
<Routes>
<Route path='*' Component={App}/>
</Routes>
</React.StrictMode>
</BrowserRouter>
);
reportWebVitals();
注意:Route必须被Routers包裹
接下来来到App.tsx文件,引用公共头部和底部,并定义好内容content部分实现页面跳转内容部分刷新,代码如下:
import React from 'react';
import { Route, Routes} from 'react-router-dom';
import Home from "./pages/home";
import About from "./pages/about";
import Product from "./pages/product";
import Header from "./component/header";
import Footer from "./component/footer";
import './App.css';
const App = () => {
return (
<div className="App">
<div className="headerComp">
<Header/>
</div>
<div className="content">
<Routes>
<Route path='/' Component={Home} />
<Route path='/product' Component={Product} />
<Route path='/about' Component={About} />
</Routes>
</div>
<div className="footerComp">
<Footer/>
</div>
</div>
);
}
export default App;
注意:引用组件名称要大写开头,路径path要和头部菜单的key值对应,
home.tsx代码如下:
import React from "react";
import { Button } from 'antd';
const App:React.FC=()=>{
return (
<div>
我是首页<Button type="primary">Button</Button>
</div>
)
}
export default App
效果如下:
注意如果要使用Ant 的图标,需要另外引入,从 4.0 开始,antd 不再内置 Icon 组件,需使用独立的包 @ant-design/icons
在项目下运行:
npm install @ant-design/icons --save
安装成功,在home.tsx文件引用
import React from "react";
import { Button } from 'antd';
import {AndroidOutlined} from '@ant-design/icons'
const App:React.FC=()=>{
return (
<div>
我是首页<Button type="primary">Button</Button>
<p>安卓: <AndroidOutlined style={{color:"green",fontSize:"24px"}} /></p>
</div>
)
}
export default App
效果: