使用Tailwind CSS切换夜间模式只需三步

2,043 阅读1分钟

我想给我的网站添加一个夜间模式(dark mode)改怎么做?

这篇文章教你如何使用 Tailwind CSS 和 React 轻松的做出切换夜间模式的效果。

第一步

在应用的根元素添加主题className,这样当它是white时就是浅色、当它是dark时就为深色。

import React from "react";

const App = () => (
 <div className={`${theme}`}>
  <div> Home </div>
 </div>
);

export default App;

第二步

将当前状态保存在localStorage中,将状态获取到后并赋值给根元素的className

import React from "react";

const App = () => {

 const theme = window.localstorage.get("theme");
 // fetch theme from localstorage


 return (
  <div classname={`${theme}`}>
   <div> <button className="dark:bg-gray-800 bg-gray-100"></button></div>
    // append the dark theme and work is done 
  </div>
)};

export default App;

第三步

在tailwind Css 的配置文件中开启夜间模式

在项目根目录下找到 tailwind.config.js ,然后将 darkMode 添加或变更为 class

// append the below line or out it after purge key
darkMode: "class", // or 'media' or 'class',

tailwind 会通过改变根元素的 className 而改变主题。

总结

借助 tailwind CSS 这样我就可以很简单实现一个切换夜间主题的功能了。

参考:tailwindcss-docs Dark Mode