react 实现进度条
使用 React 实现进度条
使用原生 HTML5 <progress> 元素
React 可以直接渲染 HTML5 的 <progress> 元素,适用于简单的进度展示:
function ProgressBar({ value, max = 100 }) {
return <progress value={value} max={max} />;
}
// 使用方式
<ProgressBar value={30} />
基于 CSS 的样式化进度条
通过 div 和 CSS 实现更灵活的样式控制:

function StyledProgressBar({ percentage }) {
return (
<div style={{ width: '100%', backgroundColor: '#e0e0e0', borderRadius: 5 }}>
<div
style={{
width: `${percentage}%`,
backgroundColor: '#4CAF50',
height: 20,
borderRadius: 5,
transition: 'width 0.3s ease'
}}
/>
</div>
);
}
// 使用方式
<StyledProgressBar percentage={75} />
使用第三方库(react-progressbar)
对于更复杂的需求,可以使用专门库如 react-progressbar:
npm install react-progressbar
实现代码:

import ProgressBar from 'react-progressbar';
function CustomProgress() {
return <ProgressBar completed={60} />;
}
动画进度条实现
结合 React 状态和 useEffect 实现动画效果:
import { useState, useEffect } from 'react';
function AnimatedProgressBar({ targetPercentage }) {
const [currentPercentage, setCurrentPercentage] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCurrentPercentage(prev =>
prev >= targetPercentage ? targetPercentage : prev + 1
);
}, 30);
return () => clearInterval(timer);
}, [targetPercentage]);
return (
<div style={{ width: '100%', backgroundColor: '#ddd' }}>
<div style={{
width: `${currentPercentage}%`,
backgroundColor: '#2196F3',
height: 20,
textAlign: 'center',
color: 'white'
}}>
{currentPercentage}%
</div>
</div>
);
}
// 使用方式
<AnimatedProgressBar targetPercentage={85} />
圆形进度条实现
使用 SVG 实现圆形进度条:
function CircularProgress({ radius = 50, strokeWidth = 10, progress }) {
const normalizedRadius = radius - strokeWidth * 2;
const circumference = normalizedRadius * 2 * Math.PI;
const strokeDashoffset = circumference - (progress / 100) * circumference;
return (
<svg height={radius * 2} width={radius * 2}>
<circle
stroke="#ddd"
fill="transparent"
strokeWidth={strokeWidth}
r={normalizedRadius}
cx={radius}
cy={radius}
/>
<circle
stroke="#4CAF50"
fill="transparent"
strokeWidth={strokeWidth}
strokeDasharray={circumference + ' ' + circumference}
style={{ strokeDashoffset }}
r={normalizedRadius}
cx={radius}
cy={radius}
/>
<text
x="50%"
y="50%"
textAnchor="middle"
dy=".3em"
fill="#333"
>
{progress}%
</text>
</svg>
);
}
// 使用方式
<CircularProgress progress={65} />
关键注意事项
- 动态进度更新时建议添加 CSS
transition属性实现平滑动画 - 确保进度值始终在 0 到 100 之间(或自定义的 max 值范围内)
- 考虑添加 ARIA 属性提升无障碍体验:
<div role="progressbar" aria-valuenow={percentage} aria-valuemin="0" aria-valuemax="100" > {percentage}% </div>






