react 中如何引入antd
安装 Ant Design
在 React 项目中安装 Ant Design 依赖包。通过 npm 或 yarn 进行安装。
npm install antd
或
yarn add antd
引入样式文件
在项目的入口文件(如 src/index.js 或 src/App.js)中引入 Ant Design 的 CSS 文件。
import 'antd/dist/antd.css';
如果使用 CSS Modules 或需要按需加载样式,可以配置 babel-plugin-import 插件。
按需加载组件
安装 babel-plugin-import 插件以支持按需加载组件,减少打包体积。
npm install babel-plugin-import --save-dev
在 babel.config.js 或 .babelrc 中配置插件。

{
"plugins": [
["import", {
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css"
}]
]
}
使用组件
在 React 组件中直接引入所需的 Ant Design 组件。
import { Button } from 'antd';
function App() {
return <Button type="primary">Primary Button</Button>;
}
export default App;
自定义主题
通过 craco 或 webpack 修改 Ant Design 的默认主题变量。
安装 craco 和 craco-antd。
npm install @craco/craco craco-antd --save-dev
在项目根目录创建 craco.config.js 文件。

const CracoAntDesignPlugin = require('craco-antd');
module.exports = {
plugins: [
{
plugin: CracoAntDesignPlugin,
options: {
customizeTheme: {
'@primary-color': '#1DA57A',
},
},
},
],
};
修改 package.json 中的脚本命令以使用 craco。
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
}
国际化配置
引入 ConfigProvider 组件并设置 locale 属性以支持国际化。
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
function App() {
return (
<ConfigProvider locale={zhCN}>
<Button type="primary">按钮</Button>
</ConfigProvider>
);
}
使用图标
从 @ant-design/icons 中引入所需图标。
npm install @ant-design/icons
在组件中使用图标。
import { SmileOutlined } from '@ant-design/icons';
function App() {
return <SmileOutlined />;
}






