使用动态 url (React.js) 的 tailwindcss 中的背景图像

Ten*_*ghe 25 javascript css typescript reactjs tailwind-css

我有一个从 API 获取的图像 url,我想将其显示为背景图像。有什么方法可以用 tailwindcss 实现这个或者我应该使用 styles 属性吗?

Ten*_*ghe 47

我想我已经找到了一个解决方案,而不是简单地使用样式属性。

<div
  style={{'--image-url': `url(${fetchedUrl})`}} 
  className='bg-[image:var(--image-url)]'>
    <!-- ... -->
</div>
Run Code Online (Sandbox Code Playgroud)

这工作得很好。

虽然看起来有点繁琐,但它可以用来启用悬停、焦点等时的背景图像,而样式属性则无法做到这一点。

className='hover:bg-[image:var(--image-url)] focus:bg-[image:var(--image-url)] ...'
Run Code Online (Sandbox Code Playgroud)

这种自定义属性的应用程序可用于实现具有顺风的动态值,例如从 API 获取的颜色。

<div
  style={{'--color': fetchedColor}} 
  className='text-[color:var(--color)]'>
    <!-- ... -->
</div>
Run Code Online (Sandbox Code Playgroud)

  • 您是否需要特定的顺风版本才能实现此功能?如果我打开 jit 模式,我可以让颜色示例工作“bg-[color:var(--color)]”,但我无法让它对示例中的图像执行任何操作。如果我将其更改为“bg-[image:var(--image)]”,则根本找不到该类。 (2认同)

use*_*848 17

我认为最好的解决方案是按照您的建议进行操作并使用样式属性。Tailwind CSS 并不真正处理动态数据,而是处理类名以向元素添加预定义样式。在不使用 style 属性的情况下,最好的方法是有条件地从元素中添加/删除 classNames,但这需要您提前知道图像 URL,这违背了从 API 获取图像的目的。

我会做:

style={{backgroundImage: `url(${fetchedImgSrc})`}}
Run Code Online (Sandbox Code Playgroud)

编辑:看起来您实际上可以使用 Tailwind 按照https://tailwindcss.com/docs/background-image执行类似于上面代码的操作。代码如下:

<div class="bg-[url('/img/hero-pattern.svg')]">
  <!-- ... -->
</div>
Run Code Online (Sandbox Code Playgroud)

  • 我已经尝试过你的第二种解决方案。但看起来如果 tailwind 包含动态值,则它不会生成类。所以我将坚持使用 style 属性。 (3认同)

小智 12

你可以只在样式中使用backgroundImage

const bag2 = "https://via.placeholder.com/500"

<div 
    className = "someting"
    style={{backgroundImage: `url(${bag2})`}}

</div>
Run Code Online (Sandbox Code Playgroud)


Ank*_*dev 5

即使使用任意值的最新实现 - 似乎它也不适用于动态 URL。就我而言,图像来自 API。如果是这种情况,请坚持使用 style 属性。

在下面的解决方案中 - bgImage 是一个道具。

<div className={`justify-center  bg-no-repeat bg-cover bg-center rounded-lg`} 
style={{ backgroundImage: `url(${bgImage})`}} >
<!-- Children here-->
</div>
Run Code Online (Sandbox Code Playgroud)