Files
skillhub-088-vercel-react-b…/rules/rendering-animate-svg-wrapper.md
2026-07-13 21:36:17 +08:00

48 lines
1.2 KiB
Markdown

---
标题: Animate SVG Wrapper Instead of SVG Element
影响: 低
影响描述: 启用硬件加速
标签: 渲染, svg, css, 动画, 性能
---
## 对 SVG 包装元素而非 SVG 本身进行动画处理
许多浏览器不支持对 SVG 元素应用 CSS3 动画的硬件加速。将 SVG 包裹在 `<div>` 中,然后对包装元素进行动画处理。
**错误做法(直接对 SVG 进行动画处理——无硬件加速):**
```tsx
function LoadingSpinner() {
return (
<svg
className="animate-spin"
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
)
}
```
**正确做法(对包装 div 进行动画处理——硬件加速):**
```tsx
function LoadingSpinner() {
return (
<div className="animate-spin">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
</div>
)
}
```
此规则适用于所有 CSS 变换与过渡(`transform``opacity``translate``scale``rotate`)。使用包装 div 可以让浏览器利用 GPU 加速,实现更流畅的动画效果。