Ant-design踩过的那些坑

Ant-design 是 React 项目中主流的前端 UI 框架,虽然文档较为全面,但是在使用中还是有很多坑的,本文就集中整理一下。

按需加载

.babelrc 文件

1
2
3
4
5
6
7
8
9
10
11
"plugins": [
"@babel/plugin-proposal-class-properties",
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": true
}
]
]

Cascader

级联选择器是一个很常用的组件,通过递归的数据结构,就可以渲染出来了,比如:

不过此次需求只有两个一级菜单,若干二级菜单。而且数据是从后端返回的,键名无法由前端定义,这样就需要前端做一下转换。代码如下

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
27
28
29
30
31
32
33
34
35
36
37
38
let options = [
{ code: 'valueA', name: 'labelA', items: [] },
{
code: 'valueB',
name: 'labelB',
items: [],
},
];
axios({
//your request
}).then((response) => {
//数据用filter做一下筛选,并将每个对象push进数组
response.data.data
.filter((item) => item.someProperty === 0)
.forEach((item) => {
options[0].items.push({
code: item.name,
name: item.age,
});
});
response.data.data
.filter((item) => item.someProperty === 1)
.forEach((item) => {
options[1].items.push({
code: item.name,
name: item.age,
});
});
});
//重点来了,此处的value:'code'和label:'name'中的code和name一定不能用value和label,也就是说 不能和规定的属性同名
<Cascader
fieldNames={{
children: 'items',
value: 'code',
label: 'name',
}}
options={options}
/>;

Spin 加载

1
2
3
4
const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
<Spin indicator={antIcon} tip=“Loading..." spinning={fileSpinVisible}>
<div></div>
</Spin>

Popover

用 overlayStyle 对样式进行简单的修改

1
2
3
<Popover overlayStyle={{ width: 88 }}>
<div className="avatar">123456</div>
</Popover>

比如一个很常见的需求,要求 popover 展开的时候,鼠标 hover 不同行,相应的行要有样式变化,那么就要去掉 antd 自带的 padding,去查找相应的元素

给 popover 添加类名,然后通过 css 文件的子元素进行样式修改,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.avatar-popover {
div {
//ant-popover-content
div {
//ant-popover-inner
div {
div {
//ant-popover-inner-content
padding: 0;
}
}
}
}
}

Select

自定义 select:

1
2
3
appearance: none;
background: url('../img/select_arrow.png') 230px center no-repeat;
background-size: 12px;
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信