一、react UI框架Antd使用
1.下载模块
npm install antd -S
2.引入antd的样式
@import '../node_modules/antd/dist/reset.css';
3.局部使用antd组件
import {Button, Calendar} from 'antd';
import {PieChartTwoTone} from '@ant-design/icons';
{/* 组件汉化配置 */}
import locale from 'antd/lib/calendar/locale/zh_CN';
<Calendar locale={locale} cellRender={ cellRender } />
<Button>antd按钮-默认</Button>
<Button type='primary'>antd按钮-主要</Button>
<Button type='primary' danger>antd按钮-危险</Button>
{/* 内嵌样式直接修改 */}
<Button type='dashed' danger style={{border:'1px dashed #78bd70'}} >antd按钮-dashed危险</Button>
<Button type='link' danger >antd按钮-link危险</Button>
<Button type='text' danger >antd按钮-text危险</Button>
<PieChartTwoTone twoToneColor="#eb2f96" spin={true} style={{fontSize:'50px'}}/>// 在index.js中配置汉化语音包
// 汉化 语言包 4.0
npm install moment -S
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
// 汉化 语言包 5.0
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
4.对应项目模块版本
node18.0.0
antd5.14.2
二、antd如何按需引入css样式以及配置
原因:上面是加载了全部的antd样式,对前端性能有隐患,所以需要antd按需引入css样式配置
1.下载指定版本插件
yarn add react-app-rewired@2.0.2-next.0
2.由于上一步可能会报下面的错,需要修改node版本,更改node版本为14.15.0或16.10.0或>=18.0.0才可以下载react-app-rewired指定模块插件
3.package.json文件修改,将react-script改为react-app-rewired
"scripts": {"start": "react-app-rewired start","build": "react-app-rewired build","test": "react-app-rewired test --env=jsdom","eject": "react-app-rewired eject"// "start": "react-scripts start",// "build": "react-scripts build",// "test": "react-scripts test",// "eject": "react-scripts eject"}
4.在项目根目录创建config-overvides.js文件用来修改默认配置
module.exports = function override(config, env) {// 使用 webpack 配置做一些事情...return config;
};
5.安装插件
yarn add babel-plugin-import// 是一个用于按需加载组件代码和样式的babel插件
yarn add customize-cra -S
yarn add less@3.11.1 less-loader@5 -S
6.修改config-overvides.js文件为下面代码
const { override, fixBabelImports, addLessLoader } = require('customize-cra');
module.exports = override(// 针对antd 实现按需打包:根据import来打包 (使用babel-plugin-import)fixBabelImports('import',{libraryName:'antd',libraryDirectory:'es',style:true,//自动打包相关的样式 默认为 style:'css'}),// 使用less-loader对源码重的less的变量进行重新制定,设置antd自定义主题addLessLoader({javascriptEnabled: true,modifyVars:{'@primary-color':'#1DA57A'},})
);
7.注释掉以下的配置,这时候直接引入组件就有对应的css,无需全局引入
@import '../node_modules/antd/dist/reset.css';
8.重新启动项目
npm start
项目中package.json中模块版本配置参考:
"dependencies": {"@testing-library/jest-dom": "^5.17.0","@testing-library/react": "^13.4.0","@testing-library/user-event": "^13.5.0","antd": "^5.14.2","babel-plugin-import": "^1.13.8","customize-cra": "^1.0.0","less": "3.11.1","less-loader": "5","moment": "^2.30.1","react": "^18.2.0","react-app-rewired": "^2.2.1","react-dom": "^18.2.0","react-scripts": "5.0.1","styled-components": "^6.1.8","web-vitals": "^2.1.4"}