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

7次阅读

共计 1070 个字符,预计需要花费 3 分钟才能阅读完成。

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);
    }
}

正文完
 0