自定义进度条(矢量图标,ts)

637 阅读1分钟

实现效果如下:

image.png

支持动态设置:

  • 高亮颜色
  • 百分比值(高亮占比)
  • icon图标

组件

import React from 'react';
import '../../style.scss';

interface Props {
  num: number, //百分值 
  backgroundColor: string, // 高亮颜色
  icon: string, // icon图标名称,这里用的阿里巴巴矢量库
}

class Precent extends React.Component<Props> {
  state = {
    styleCommon: null,
    styleActive: null,
    styleGray: null
  }
  componentDidMount() {
    const { num, backgroundColor } = this.props;
    this.setState({
      // 图标全部高亮
      styleCommon: {
        "backgroundImage": `linear-gradient(to right, ${backgroundColor} 100%, transparent 0%)`,
        "WebkitBackgroundClip": "text",
        "WebkitTextFillColor": "transparent"
      },
      // 图标部分高亮
      styleActive: {
        "backgroundImage": `linear-gradient(to right, ${backgroundColor} ${(num%10 ? (25+(num-Math.floor(num/10)*10)*5) : 100)+'%'}, #3A5A71 ${(num%10 ? (75 - (num-Math.floor(num/10)*10)*5) : 0) + '%'})`,
        "WebkitBackgroundClip": "text",
        "WebkitTextFillColor": "transparent"
      },
      // 图标全部为灰
      styleGray: {
        "backgroundImage": 'linear-gradient(to right, #3A5A71 100%, transparent 0%)',
        "WebkitBackgroundClip": "text",
        "WebkitTextFillColor": "transparent"
      }
    })
  }
  render() {
    const { styleCommon, styleActive, styleGray } = this.state;
    const { icon, num } = this.props;
    const indexActive = Math.ceil(num/10);
    return (
      <div className="Precent">
        {
          [1,1,1,1,1,1,1,1,1,1].map((item, index) => 
            <i className={`iconfont ${icon}`} style={(indexActive-1)>index ? styleCommon : (((indexActive-1)===index) ? styleActive : styleGray)}></i>
          )
        }
      </div>
    );
  }
}

export default Precent;