我最近刚学了React和Tailwind用于项目,我还是个初学者。我想让一个元素有背景图片作为自定义类变量,就像这样:
<div className="bg-[url(`https://example.com/${variable}.png`)]"></div>
但是,由于Tailwind清除类名,这是否有可能呢?我希望我没有漏掉什么,但现在对我来说似乎不可行。
我最近刚学了React和Tailwind用于项目,我还是个初学者。我想让一个元素有背景图片作为自定义类变量,就像这样:
<div className="bg-[url(`https://example.com/${variable}.png`)]"></div>
但是,由于Tailwind清除类名,这是否有可能呢?我希望我没有漏掉什么,但现在对我来说似乎不可行。
<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>
);
}
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>
</>
);
}
https://example.com/${variable}.png
)]" - MWOclassName="bg-[url('https://example.com/${variable}.png')]"
上仍然无法工作。 - Vitroidbg-[url('https://example.com/${variable}.png')]
类。 - Vitroid<div style={\
background: url(https://example.com/${variable}.png\`}>` 替代。 - ShamPooSham