【问题标题】:How can i dynamically change images as Background in TailwindCSS?如何在 TailwindCSS 中动态地将图像更改为背景?
【发布时间】:2022-07-25 18:26:59
【问题描述】:

我想做一个旋转木马,背景在变化,我不想用<img/>标签!我按照文档中的描述设置值:https://tailwindcss.com/docs/background-image#arbitrary-values

我的代码:

import React from 'react';

type CarouselProps = {
  img: string;
};

const Carousel = ({ img }: CarouselProps) => {
  return (
    <div
      className={`col-span-full bg-[url(${img})] bg-cover grid grid-cols-12 gap-6`}
    > ...
    </div>
);
};

当我设置我传递给硬编码的组件的字符串时,它可以工作,但是当我使用花括号和 $ 时它不会。此外,我不想在 tailwind.conf.js 中定义我的背景图像

错误:

ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5]
.use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!
./node_modules/source-map-loader/dist/cjs.js!./src/index.css) 9:36-70

【问题讨论】:

    标签: reactjs tailwind-css


    【解决方案1】:

    我不想在 tailwind.conf.js 中定义我的背景图像

    好吧,你必须这样做。不支持您尝试执行的操作。

    Tailwind 故意扫描您的源代码以查找类的方式 非常简单——我们实际上并不解析或执行你的任何代码 它所用的语言,我们只是使用正则表达式来 提取每个可能是类名的字符串。

    因此,tailwind 不知道您的 React 代码的实际含义。所以它根本行不通。


    Tailwind does not support dynamic class names:

    不要动态构造类名

    <div class="text-{{ error ? 'red' : 'green' }}-600"></div>
    

    您应该customise your theme 包含图片网址:

    您可以通过编辑 您的 tailwind.config.js 文件的 theme.backgroundImage 部分:

    tailwind.config.js

    module.exports = {
      theme: {
        extend: {
          backgroundImage: {
            'hero-pattern': "url('/img/hero-pattern.svg')",
            'footer-texture': "url('/img/footer-texture.png')",
          }
        }
      }
    }
    

    【讨论】:

    • 我可以这样做,但我有一个 CMS 作为后端,我不确定如何将这些图像导入 Tailwind 配置。是否可以使 tailwindconfig 异步?
    • 不,不是。顺风你根本无法做到这一点。您需要改用标准 CSS,这应该很简单,只需使用 style 属性?
    【解决方案2】:

    解决方案是使用style 属性。感谢您的帮助:)

    <div
          className="col-span-full bg- bg-cover grid grid-cols-12 gap-6"
          style={{
            backgroundImage: `url(${img})`,
          }}
        >
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      相关资源
      最近更新 更多