如何在nextjs中使用按钮点击更改daisyUI主题?

kmynzznz  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(219)

根据daisyUI documentation,我们可以通过在<html>中更新data-theme变量的值来更新主题,如下所示:<html data-theme="cupcake"></html>
通过查看Custom Document的nextjs文档,我不知道如何动态更新data-theme

bxpogfeg

bxpogfeg1#

我们可以在npm包next-themes的帮助下,在nextjs中更新<html>标签上的data-theme变量,如下所示:

// _app.tsx
import { ThemeProvider } from "next-themes";

const MyApp = ({
  Component,
  pageProps: { ...pageProps },
}) => {
  return (
      <ThemeProvider>
        <Component {...pageProps} />
      </ThemeProvider>
  );
};

export default MyApp;
// header.tsx
import { MoonIcon, SunIcon } from "@heroicons/react/24/solid";
import { useTheme } from "next-themes";

export default function Header() {
  const { theme, setTheme } = useTheme();

  return (
    <div>
      {theme === "business" ? (
        <div
          className="flex-1 lg:flex-none"
          onClick={() => setTheme("emerald")}
        >
          <SunIcon className="h-8 w-8 cursor-pointer text-green-400 sm:h-10 sm:w-10" />
        </div>
      ) : (
        <div
          className="flex-1 lg:flex-none"
          onClick={() => setTheme("business")}
        >
          <MoonIcon className="h-8 w-8 cursor-pointer text-green-400 sm:h-8 sm:w-8" />
        </div>
      )}
    </div>
  );
}

Next-themes在执行setTheme('value')函数时默认更改<html>标记上的data-theme的值

相关问题