在 Tailwind 的类名中使用 React 变量。

9

我最近刚学了React和Tailwind用于项目,我还是个初学者。我想让一个元素有背景图片作为自定义类变量,就像这样:

<div className="bg-[url(`https://example.com/${variable}.png`)]"></div>

但是,由于Tailwind清除类名,这是否有可能呢?我希望我没有漏掉什么,但现在对我来说似乎不可行。


我认为你多了一个闭合方括号?className="bg-[url(https://example.com/${variable}.png)]" - MWO
这是我的错,我复制错误了。在 className="bg-[url('https://example.com/${variable}.png')]" 上仍然无法工作。 - Vitroid
没有错误,当网站全部加载完毕时检查它只有那个元素上的 bg-[url('https://example.com/${variable}.png')] 类。 - Vitroid
6
虽然我的代码生成的类看起来正确,但是tailwind不会为它生成CSS。我得出结论这是不可能的,因为Tailwind不会在运行时生成任何CSS,所以它无法创建所有可能的字符串插值所需的类。Tailwind只会在编译期间分析字符串并为其创建相应的类。你应该使用<div style={\background: url(https://example.com/${variable}.png\`}>` 替代。 - ShamPooSham
非常感谢,那个起作用了。 - Vitroid
显示剩余2条评论
2个回答

1
Tailwind有一个名为“safelisting”的功能,可能会为您提供所需的功能-请在文档中此处查看
话虽如此:
1- 在同一元素上同时使用className和style属性没有问题-例如,您可以拥有<div className="w-full" style={`background: url(https://example.com/${variable}.png`}> 2- 根据您使用的React版本,您可能最好使用像Next.js的Image这样的组件来优化图像,而不是通过CSS设置背景。以下是我的做法:
import Image from "next/image";

export default function MyBackground(props) {
  return (
    <div
      className="z-0 absolute inset-0 w-full h-full flex justify-center items-center"
    >
      <Image
        placeholder="blur"
        alt={props.alt}
        src={props.src}
        className="h-full w-full object-cover"
      />
    </div>
  );
}



0
你可以为此定义一个不同的变量。这样,你就可以相应地操作该值并使用该变量来设置该元素的样式属性。代码看起来大致如下:
const YourComponent = () => {

    //the variable named variable will hold the dynamic value as per your need
    let elementStyle = "bg-[url(`https://example.com/" + variable + ".png";

    return (<>
                <div className={elementStyle}"></div>
            </>
    );
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接