js 部分
import React, { Component } from 'react' import './index.less'; export default class index extends Component { constructor(props) { super(props); this.state={ progressValue: 0, // 進度條背景寬度 percentage: 0, // 進度條百分比 } } handleBtn = () => { let { progressValue, percentage} = this.state; let timer = null; if (timer == null) { timer = setInterval(() => { progressValue += 10; // 這里的算法很重要,進度條容器的寬度為 400px 所以這里除以400再乘100就能得到 1-100的百分比了。 percentage = Math.round(progressValue/400*100); if (progressValue >= 400) { percentage=100; progressValue=400; clearInterval(timer) } this.setState({ progressValue, percentage }) }, 100); } } render() { return ( <div className='progress-box'> <div className='progress-group'> <span>{this.state.percentage}%</span> <div className='progress-bg' style={{ width: this.state.progressValue}}></div> </div> <button onClick={this.handleBtn}>安裝</button> </div> ) } }
css 部分
.progress-box { padding: 20px; width: 400px; .progress-group { width: 100%; height: 30px; position: relative; border: 1px solid #D72672; .progress-bg { width: 0px; height: 100%; display: flex; justify-content: center; align-items: center; background: #D72672; } span { position: absolute; } } button { margin-top: 20px; } }