背景:
已经有一个具有基本功能的switch组件,但是缺少loading功能。需求需有实现组件的loading状态
基本思路:
- 理解Switch组件的基本构成:trigger + children
- 确定loading放置位置: 因为最后loading是放置于switch上trigger位置,所以基于trigger来写
- 在不修改html(包括render)中dom的情况下, 可以使用伪元素:after 和 :before来实现想要在的位置插入元素
// style.scss 文件, react 配置了scss和 css module
// $scn === switch-component-name 用scn来表示原来Switch组件的类名
:global {
.#{$scn}-loading {
line-height: 1;
}
// 核心代码 : 1. 通过absolution定位(已知switch组件有positon 属性)获取位置 2. 通过css3 中animation属性实现旋转 3. 通过font-family改变子体,映射成loading样子
//
&:before {
position: absolute;
top: 0;
bottom: 0;
z-index: 2;
display: block;
width: 16px;
height: 16px;
line-height: 16px;
margin: auto;
content: '\e900';
font-family: NextIcon;
font-size: 16px;
color: red;
animation: loadingCircle 1s infinite linear;
}
// 核心代码结束
}
- 封装switch并且暴露接口
// 注意scn变量对应字符串要和scss文件中scn变量对应字符串全等
const prefix = `${scn}`;
export default class ExtSwitch extends React.Component {
render() {
const { className, loading, disabled, ...restProps } = this.props;
return (
<Switch
// 核心代码 在类名中增加loading状态下的类名, 并且修改disabled当loading时候disabled也为true
className={classnames(className, { [`${prefix}-loading`]: loading })}
disabled={disabled || loading}
{...restProps}
/>
);
}
}
- 完善建议: 可以增加switch-on 和 switch-off的样式