我在项目中第一次使用tailwind css
。我知道如何使用tailwind-config
为"颜色"、"边界半径"等创建变量。
但在这种情况下,
background-color
、color
等将通过api
,因此response
被设置为state
变量。
现在,我实际上需要将state
变量的值添加到tailwind-config
中,以便tailwind-config
中background-color
、color
等的变量获得其值,因此使用它的每个元素都会相应地更改。
所以在做了一些R&D和改变视角后。
以下是解释
场景:
- 颜色来自API响应
- 我希望它们适合
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)",
},
},
},
};
primary
和secondary
颜色来自我们的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;
}