跳到主要內容

輕鬆轉換:SVG To JSX

將 SVG 標記轉換為 React 函式元件:SVGO 先在瀏覽器中最佳化 SVG,再由 SVGR 在瀏覽器本機轉換。屬性改為 camelCase(stroke-width 變為 strokeWidth),數值尺寸變為數字,並在根 <svg> 上展開 {...props}。

把從 Figma 或 Illustrator 匯出的圖示變成 React 元件。

SVG

適用場景

  • 把從 Figma 或 Illustrator 匯出的圖示變成 React 元件。
  • 在把 SVGR 加入構建流程之前,檢視 SVGR 會如何改寫 SVG。

使用方法

  1. 貼上 SVG 標記或載入 .svg 檔案;不是有效 SVG 的輸入會被拒絕並顯示錯誤。
  2. 開啟設定,可關閉 SVGO 最佳化,或切換 remove title、merge paths 等外掛;編輯器下方的預覽會對比原始 SVG 和最佳化後的 SVG。
  3. 複製元件並重命名 SvgComponent;通過 props 傳入 className、width 或 fill。

SVG

<!-- Generator: Adobe Illustrator -->
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
  <title>Minus</title>
  <path fill="none" stroke="currentColor" stroke-width="2.000" stroke-linecap="round" d="M5.000 12.000 L19.000 12.000"/>
</svg>

React 元件(JSX)

import * as React from "react"
const SvgComponent = (props) => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width={24}
    height={24}
    viewBox="0 0 24 24"
    {...props}
  >
    <path
      fill="none"
      stroke="currentColor"
      strokeLinecap="round"
      strokeWidth={2}
      d="M5 12h14"
    />
  </svg>
)
export default SvgComponent

功能與限制

SVGO 與 SVGR 都在瀏覽器本機執行,SVG 標記不會上傳至轉換伺服器。

在預設設定下,註釋、<title>、<desc> 和編輯器後設資料會被移除,路徑資料會被縮短(M5.000 12.000 L19.000 12.000 變為 M5 12h14)。關閉最佳化即可按貼上內容原樣轉換。

style 字串變為樣式物件,class 變為 className。

輸出面向 React DOM;如需 react-native-svg,請使用 SVG 轉 React Native。

FAQ

為什麼根元素保留了 width 和 height?

SVGO 設定中的 remove dimensions 預設關閉,且 SVGR 使用預設選項,因此尺寸會以數字形式保留(width={24})。由於 {...props} 位於其後,可以通過 props 覆蓋。

fill="currentColor" 能讓我用 CSS 設定顏色嗎?

能。currentColor 會被保留,因此圖示會跟隨父元素的 CSS color。路徑中寫死的顏色不會被替換。

為什麼元件裡沒有 <title>?

SVGO 的 remove title 預設開啟。如果出於無障礙需要 <title>,請在設定中關閉它,或完全關閉最佳化。

能輸出 TypeScript 嗎?

不能。本頁輸出不帶型別註解的 JavaScript 元件。

規範與參考資料