gpt4 book ai didi

reactjs - 如何在 React 项目中使用 daisyUI 和 tailwindcss 更改主题?

转载 作者:行者123 更新时间:2023-12-02 18:07:35 35 4
gpt4 key购买 nike

我似乎无法在任何文档中找到解决此问题的方法。我想要的只是有一个按钮切换,可以在明暗模式之间切换。

最佳答案

其实不需要安装额外的npm包来实现主题切换。

如果您想要实现的只是切换,您可以在 tailwind.config.cjs 文件中列出所需的主题,如下所示:

plugins: [require('daisyui')],
daisyui: {
themes: ['light', 'dark'],
},

然后在你的组件中,有一个状态,一个切换函数和一个 useEffect 处理属性注入(inject)到文档的 HTML 标记中(我们希望根据 daisyUI 文档将全局主题作为 html 元素中的一个属性: https://daisyui.com/docs/themes/ )

function MyAwesomeThemeComponent() {
const [theme, setTheme] = React.useState('light');
const toggleTheme = () => {
setTheme(theme === 'dark' ? 'light' : 'dark');
};
// initially set the theme and "listen" for changes to apply them to the HTML tag
React.useEffect(() => {
document.querySelector('html').setAttribute('data-theme', theme);
}, [theme]);
return (
<label className="swap swap-rotate">
<input onClick={toggleTheme} type="checkbox" />
<div className="swap-on">DARKMODE</div>
<div className="swap-off">LIGHTMODE</div>
</label>
);
}

关于reactjs - 如何在 React 项目中使用 daisyUI 和 tailwindcss 更改主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72926946/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com