热搜:fiddler git ip 代理 m1
历史搜索

怎么在React中更改SVG的颜色?

游客2024-08-25 12:03:01

在 React 中更改 SVG 的颜色

要在 React 中更改 SVG 的颜色,请执行以下操作:

  • 不要在 SVG 上设置fillstroke属性。
  • 将 SVG 作为组件导入。
  • 在组件上设置fillstroke道具。
import {ReactComponent as MyLogo} from './my-logo.svg';

export default function App() {
  return (
    <div>
      <MyLogo fill="black" stroke="yellow" />
    </div>
  );
}

举例

下面是 SVG 组件,这里命名为 my-logo.svg:

<svg width="400" height="400">
  <circle cx="100" cy="100" r="50" stroke-width="5" />
</svg>

请注意,我们没有在 svg 元素上设置fillstroke属性。

如果它们尚未在 svg 中定义的话,fillstroke将仅在通过组件参数设置时应用。

fill设置对象内部的颜色,stroke设置围绕对象绘制的线的颜色。

创建一个以colors为 props 渲染 SVG 的组件

或者,可以将 SVG 粘贴到组件中,并将 colors 作为 props。

function MyLogo({fill, stroke}) {
  // 👇️ SVG 粘贴到组件中
  // 
  return (
    <svg fill={fill} stroke={stroke} width="400" height="400">
      <circle cx="100" cy="100" r="50" stroke-width="5" />
    </svg>
  );
}

export default function App() {
  return (
    <div>
      <MyLogo fill="black" stroke="yellow" />
    </div>
  );
}

怎么在React中更改SVG的颜色? 1

上面的代码示例实现了相同的结果,但我们将 SVG 直接存储在组件中,而不是从具有 SVG 扩展名的文件中导入。

请注意,MyLogo 组件将 fill 值和 stroke 值作为 props,并将它们应用于 svg 元素。

标签:React