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