React 之antd

时间:2025-01-20 19:10:06

React 之antd

参考网站:/docs/react/use-with-create-react-app-cn

create-react-app 是业界最优秀的 React 应用开发工具之一。在 create-react-app 创建的工程中使用 antd 组件,并自定义 webpack 的配置以满足各类工程化需求。

1.安装和初始化

$ npm i yarn 					##安装yarn
$ yarn create react-app demo 	##文件名:demo;自动初始化一个脚手架并安装 React 项目的各种必要依赖
$ cd antd-demo  				##进入项目
$ yarn start   					##启动项目此时浏览器会访问 http://localhost:3000/ ,看到 Welcome to React 的界面
  • 1
  • 2
  • 3
  • 4

2.引入antd

$ yarn add antd					 ## 安装并引入 antd
$ npm i antd -S					 ## 安装并引入 antd
  • 1
  • 2

修改 src/,引入 antd 的按钮组件

import React, { Component } from 'react';
import Button from 'antd/es/button';
import './';

export default class App extends Component {
  render() {
    return (
      <div className="App">
        <Button type="primary">Button</Button>
      </div>
    );
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

修改 src/,在文件顶部引入 antd/dist/

@import '~antd/dist/';

.App {
  text-align: center;
}
  • 1
  • 2
  • 3
  • 4
  • 5

3.按需引入配置

1).使用customize-cra

$ yarn add react-app-rewired customize-cra 				  ## 安装 customize-cra
  • 1

更改

"scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test",
+   "test": "react-app-rewired test",
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在项目根目录创建一个 用于修改默认配置。

module.exports = function override(config, env) {
  // do stuff with the webpack config...
  return config;
};
  • 1
  • 2
  • 3
  • 4

2).使用 babel-plugin-import

$ yarn add babel-plugin-import
  • 1

修改

+ const { override, fixBabelImports } = require('customize-cra');

//-  = function override(config, env) {
//-   // do stuff with the webpack config...
//-   return config;
//- };
+ module.exports = override(
+   fixBabelImports('import', {
+     libraryName: 'antd',
+     libraryDirectory: 'es',
+     style: 'css',
+   }),
+ );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

移除前面在 src/ 里全量添加的 @import '~antd/dist/'; 样式代码,并且按下面的格式引入模块。

 // src/
  import React, { Component } from 'react';
//- import Button from 'antd/es/button';
+ import { Button } from 'antd';
  import './';

   export default class App extends Component {
    render() {
      return (
        <div className="App">
          <Button type="primary">Button</Button>
        </div>
      );
    }
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

4.国际化

import { LocaleProvider } from 'antd'
import zhCN from 'antd/es/locale-provider/zh_CN';

render(
    // 国际化-- locale={zhCN} 汉语
    <LocaleProvider locale={zhCN}>
        <App />
    </LocaleProvider>,
    document.querySelector('#root')
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10