Antd的基本使用

进入Antd官方网站查看具体使用文档

安装和初始化

在react项目中进行安装yarn add antd或者npm i antd安装

简单使用

在App.js文件中引入按钮并使用
注意,这里还需要引入css样式import 'antd/dist/antd.css'

1
2
3
4
5
6
7
8
9
10
11
12
import React, { Component } from 'react'
import { Button } from 'antd'; //引入按钮
import 'antd/dist/antd.css'; //还需要引入css样式
export default class App extends Component {
render() {
return (
<div>
<Button>我是antd的按钮哦</Button>
</div>
)
}
}

Antd的高级配置

按需加载目的是不用引入import 'antd/dist/antd.css'各个组件就可以拥有自己的css样式

  • 前提需要安装react-app-rewired / customize-cra

    1
    2
    yarn add react-app-rewired
    yarn add customize-cra
  • 高能预警:
    yarn add less less-loader@5.0.0(下载5版本的,并按照官网提示操作。6版本会报错)

  • 需要配置package.json文件

    1
    2
    3
    4
    5
    6
    "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
    }
  • 在项目根目录下增加一个文件config-overrides.js

  • 再去安装 babel-plugin-import
    yarn add babel-plugin-import

  • 找到config-overrides.js文件进行配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    const {
    override,
    addLessLoader, // less配置函数
    fixBabelImports, // 按需加载配置函数
    addBabelPlugins // babel插件配置函数
    } = require('customize-cra')

    module.exports = override(
    ...addBabelPlugins( // 支持装饰器
    [
    '@babel/plugin-proposal-decorators',
    { legacy: true}
    ]
    ),
    fixBabelImports('import', { // antd 按需加载
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true //自动打包相关的样式 默认为 style:'css'
    }),
    addLessLoader(
    {
    javascriptEnabled: true,
    modifyVars: { '@primary-color': 'red' }
    }
    ),
    )
  • 现在从antd组件库里面引入组件,那么组件就拥有各自的样式了。

项目使用less

直接新建less文件,在js文件中导入即可使用

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React from 'react';
import './App.css';
import { Button } from 'antd';
import './demo.less'

function App() {
return (
<div className="App">
<Button type="primary">点击</Button>
</div>
);
}

export default App;

demo.less

1
2
3
4
span {
color: red;
}

运行项目测试如下:

去除antd运行警告

react使用antd警告:Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance

警告原因:

是因为 react 中的严格模式: StrictMode

解决办法:

index.js中挂载 App 的外面有这样一个标签
只要把这个标签删除掉就可以了