gpt4 book ai didi

reactjs - React 和 Tailwind CSS 中的 SVG — 填充 : "currentColor" not working

转载 作者:行者123 更新时间:2023-12-05 04:48:43 29 4
gpt4 key购买 nike

我正在尝试使用 Tailwind CSS 让 SVG 在暗模式下更改颜色。这意味着我必须使用像 text-white 这样的类来设置 SVG 的填充颜色(转换为 --tw-text-opacity: 1; color: rgba(255, 255, 255 , var(--tw-text-opacity)); 在纯 CSS 中)。然后我可以添加另一个 Tailwind 类,如 dark:text-black,当用户启用深色模式时,它应该使 SVG 变黑。

然而,即使 SVG 被正确格式化为使用 fill: currentColor,填充也不匹配父元素的 currentColor(文本颜色)(一个 img 标签)。

我做错了什么?

HTML

<img
className="w-auto h-12 mx-auto mt-12 text-black rounded-full p-x4 dark:text-white"
src="/brand/cerebrum-full.svg"
/>

SVG

<style type="text/css">
.currentColorFill{fill:currentColor !important;}
</style>
<g>
<path
className="currentColorFill"
d="M284.6,124.1v-0.2c0-23.8,17.9-43.3,43.6-43.3c15.8,0,25.2,5.3,33,12.9l-11.7,13.5c-6.5-5.9-13-9.4-21.4-9.4
c-14.1,0-24.3,11.7-24.3,26v0.2c0,14.3,9.9,26.3,24.3,26.3c9.6,0,15.4-3.8,22-9.8l11.7,11.8c-8.6,9.2-18.2,14.9-34.3,14.9
C302.9,167.2,284.6,148.2,284.6,124.1z"
/>
<path class="currentColorFill" d="M412.3,25.5h3.4v6c1.7-3.8,5-6.6,9.3-6.4v3.7h-0.3c-5,0-9.1,3.6-9.1,10.5v9.1h-3.4V25.5z"/>

</g>

最佳答案

(搞清楚后自己回答...)

发生这种情况是因为您使用图像标签嵌入了 SVG。我建议使用类似这样的组件从组件导入 SVG svg-to-react-cli NPM package .

假设您的 SVG 名为“AcmeLogo”,您已将其另存为 AcmeLogo.svg .以下是转换您的 AcmeLogo.svg 的步骤文件到 React 组件:

  1. 运行 npm install -g svg-to-react-cli在你的终端
  2. 运行 svgtoreact <PATH_TO_SVG> <PATH_TO_EXPORT_REACT COMPONENT>像这样:
    • svgtoreact /path/to/AcmeLogo.svg /path/to/AcmeLogo.js

现在,导入 AcmeLogo.js进入你的 React 页面并将你的类添加到组件中,如下所示:

import AcmeLogo from "components/AcmeLogo.js";

<AcmeLogo className="w-auto h-12 mx-auto mt-12 text-black p-x4 dark:text-white" />

这应该有效!现在您可以尝试从浅色模式更改为深色模式,您应该会看到 SVG 的填充颜色根据文本颜色发生变化。

关于reactjs - React 和 Tailwind CSS 中的 SVG — 填充 : "currentColor" not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67963274/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com