一、React中使用Antd
antd官网:https://ant.design/docs/react/introduce-cn
step1:安装antd :【cnpm install antd --save】/ 【 yarn add antd】
step2:在react项目的css中引入antd的css:
@import '~antd/dist/antd.css';
step3:开始使用:例如使用Button组件:
在组件中引入:import { Button } from 'antd';
<Button type="primary">hello</Button>
二、React中使用Antd高级配置—按需引入css样式
上面的例子实际上加载了全部的 antd 组件的样式(对前端性能是个隐患)。
step1:安装antd :【cnpm install antd --save】/ 【 yarn add antd】
step2:安装react-app-rewired(一个对 create-react-app 进行自定义配置的社区解决方案):
【cnpm install react-app-rewired --save】/ 【 yarn add react-app-rewired】
step3:修改package.json文件,把"scripts"下的 "react-scripts" 全部改成 "react-app-rewired"
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
step4:在项目根目录创建一个 config-overrides.js 文件,用于修改默认配置。 config-overrides.js文件内容如下:
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
step5:安装babel-plugin-import(是一个用于按需加载组件代码和样式的 babel 插件):
【cnpm install babel-plugin-import --save】/ 【 yarn add babel-plugin-import】
step6:修改 config-overrides.js 文件,将原来内容删掉,添加下面内容:
const { override, fixBabelImports } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
);
step7:移除src/App.css 里全量添加的 @import '~antd/dist/antd.css'; 直接引入组件使用就会有对应的css。最后重启【cnpm start】访问页面,这样就可以实现按需加载。
三、升级4.X版本:
现在antd已经到了4.X版本,如果我们想从3.X升级到4.X,官网介绍如下:
但是我们实际操作中,需要做下面的步骤:
step1:更新 antd 版本:
通过查看antd更新日志(https://ant.design/changelog-cn),查看最新版本号,目前是4.5.2
然后输入命令行:【cnpm install --save antd@4.5.2】
step2:更新 react 版本:
通过查看react更新日志(https://github.com/facebook/react/blob/master/CHANGELOG.md),查看最新版本号,目前是16.13.0
然后输入命令行:【cnpm install --save react@16.13.0 react-dom@16.13.0】
注意:旧版 Icon 使用方式将被废弃,旧代码可能会出现下面的错误“Attempted import error: 'Icon' is not exported from 'antd'.”
可以先把Icon的使用代码给去掉,然后再参照官网进行修改。
仍然可以通过兼容包继续使用Icon:import { Icon } from '@ant-design/compatible';
如果启动的时候报错,可以把 node_modules 删掉,再重新安装。
如果用到的组件比较多,还有部分在4.X新版本需要重构的,那么可以用下面的命令进行升级(这种还未亲测过,有机会再试):