繁体   English   中英

如何将变量从 JavaScript 文件传递到 tailwind.config 文件?

[英]How to pass variables form JavaScript file to tailwind.config file?

我在我的项目中第一次使用tailwind css 我知道如何使用tailwind-config为“颜色”、“边框半径”等创建变量。

但在这种情况下,

background-colorcolor等将通过api因此response设置为state变量。

现在我实际上需要将state变量的值添加到 tailwind tailwind-config中,以便 tailwind- tailwind-config中的background-colorcolor等变量获得它的值,并且由于使用它的每个元素都会相应地发生变化。

所以现在做了一些研发,换了个视角,问题就解决了。

这是解释
场景:

  1. Colors 来自 API 响应。
  2. 我希望它们适合tailwind.config.js ,以便以后可以在项目的各个地方使用这些变量。

所以变化基本上在于项目的2个文件

  • tailwind.config.js
  • app.js (或任何你进行 API 调用的地方)

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
    content: ["./src/**/*.{js,jsx}"],
    darkMode: "class",
    theme: {
        extend: {
            colors: {
                primary: "var(--bg-nav)",
                secondary: "var(--bg-color)",
            },
        },
    },
};

primarysecondary colors 来自我们的app.js文件,语法与我们在CSS中使用的语法相同

应用程序.js

import { useEffect } from "react";

const App = () => {

useEffect( () => {
    //make an API call and set the response data to a variable
    const brandColor = "#0ff0f0";
    const bgColor = "#a5cd3e";
}, [])

    return (
        <section>
            <style
                dangerouslySetInnerHTML={{
                    __html: ` :root {
                             --bg-nav: ${brandColor};
                             --bg-color: ${bgColor}
                           }`,
                    }}
            />  
        </section>
    );
};

危险地设置InnerHTML

这将使事情按预期工作。

但是index.css没有变化只是为了交叉检查这里是 index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@import "./fonts/stylesheet.css";

@layer base {

    ul,
    ol {
        list-style: revert;
    }
}

body {
    max-width: 2000px;
    margin: auto;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM