在 React 中,我有一個 svg 檔案,例如 mySVG.svg
<svg width="50" height="50" viewBox="0 0 50 50" xmlns="http://www.w3.org/2000/svg">
<rect id="Unit1" class="class1" x="0" y="0" width="10" height="10" fill="blue"/>
<rect id="Unit2" class="class1" x="10" y="10" width="10" height="10" fill="blue"/>
<rect id="Unit3" class="class2" x="20" y="20" width="10" height="10" fill="blue"/>
</svg>
然后,在組件檔案中Example.tsx,我想根據傳入的 props 動態設定 svg 的顏色
import { ReactComponent as mySvg} from 'assets/mySVG.svg';
export function Example(props:{highlighted:string}):ReactElement {
if (props.highlighted === 'Unit1') {
return (
<mySvg
//set unit 1 fill color to red
/>
);
}
return (
<mySvg />
);
}
我將如何根據 svg 路徑的 id 和 className 動態設定 svg 的填充顏色?
使用定義的顏色匯入靜態 css 檔案將不起作用,因為我需要它動態作業。
uj5u.com熱心網友回復:
您可以操作要匯入的檔案,但我認為最簡單的方法是將 svg 創建為組件。
在此處查看示例:https : //codesandbox.io/s/happy-galois-1tfce
uj5u.com熱心網友回復:
首先,我想向您推薦這個站點,它將普通的 svg 代碼轉換為 jsx 組件。使用 svg 將必要的 props 傳輸到組件就足夠了
mySVG.jsx:
import * as React from "react"
function mySVG({color = "#000000", className = "", width = 50, height = 50}) {
return (
<svg
className={className}
width={width}
height={height}
xmlns="http://www.w3.org/2000/svg"
>
<path fill={color} d="M0 0h10v10H0zM10 10h10v10H10z" />
<path fill={color} d="M20 20h10v10H20z" />
</svg>
)
}
export default mySVG
并使用 svg 將必要的資料傳輸到您的組件
import mySVG from "/you/path/mySVG"
// other code....
return (
<mySVG
color="#ffffff"
height={100}
width={100}
className="my-svg-style"
/>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/338060.html
