react骨架屏实现
实现 React 骨架屏的常用方法
使用第三方库(如 react-loading-skeleton)
安装库:npm install react-loading-skeleton
引入并使用:
import Skeleton from 'react-loading-skeleton';
const MyComponent = () => (
<div>
<Skeleton height={20} width={200} />
<Skeleton count={3} height={10} />
</div>
);
该库提供高度可定制的骨架块,支持颜色、尺寸等参数调整。
手动实现 CSS 骨架屏 通过 CSS 动画和占位元素模拟加载状态:
.skeleton {
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
from { background-position: 200% 0; }
to { background-position: -200% 0; }
}
在组件中应用:
<div className="skeleton" style={{ width: '100%', height: '50px' }} />
结合 Suspense 和懒加载 React 18+ 推荐模式:
import { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./Component'));
const App = () => (
<Suspense fallback={<SkeletonLoader />}>
<LazyComponent />
</Suspense>
);
动态内容替换策略 在数据加载完成后切换显示:
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetchData().then(() => setIsLoading(false));
}, []);
return (
<div>
{isLoading ? <SkeletonLayout /> : <ActualContent />}
</div>
);
最佳实践建议
- 保持骨架屏结构与实际 UI 布局一致
- 避免过度动画影响性能
- 为不同屏幕尺寸设计响应式骨架
- 使用 CSS 变量方便主题切换
- 考虑骨架屏的 accessibility(添加 aria-live 属性)







