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



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

但在这种情况下,

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

现在,我实际上需要将state变量的值添加到tailwind-config中,以便tailwind-configbackground-colorcolor等的变量获得其值,因此使用它的每个元素都会相应地更改。

所以在做了一些R&D和改变视角后。

以下是解释
场景:

  1. 颜色来自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颜色来自我们的app.js文件,语法与我们在CSS中使用的语法相同

App.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>
);
};

危险的SetInnerHTML

这将使事情按预期进行。

然而,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;
}

最新更新