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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章