30行代码实现一个进度条组件

30行js和30行css实现一个进度条组件,关键在于运用css变量如何使用css变量

预览图

代码

Javascript

import React from 'react';
import PropTypes from 'prop-types';
import Styles from './main.module.scss';

/**
 *
 * 传入percent,生成进度条
 * @param {*} { percent } 进度条进度控制
 * @bgColor {*} { percent } 进度条背景颜色
 * @returns jsx
 */
export default function ProgressBar({ percent, bgColor }) {
    if (percent < 0 || percent > 100) {
        console.error(new Error('percent value must between 0 - 100'));
        return null;
    }
    return (
        <div 
            className={Styles.progress} 
            style={{ '--percent': percent, '--bgColor': bgColor }} 
        />
    );
}

ProgressBar.propTypes = {
    percent: PropTypes.number,
    bgColor: PropTypes.string,
};
ProgressBar.defaultProps = {
    percent: 50,
    bgColor: '#2486ff',
};

CSS

.progress {
    width: 100%;
    height: 17px;
    margin: 5px;
    color: #fff;
    background-color: #f1f1f1;
    font-size: 12px;
}
.progress::before {
    counter-reset: percent var(--percent);
    /*文字显示*/
    content: counter(percent) "%"; 
    display: inline-block;
    /*宽度计算*/
    width: calc(100% * var(--percent) / 100); 
    max-width: 100%;
    height: inherit;
    text-align: right;
    background-color: var(--bgColor);
    transition:width 2s;
    animation: progress 1s ease forwards;
}
@keyframes progress {
    from {
        width: 0;
    }

    to {
        width: calc(100% * var(--percent) / 100);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章