我的网站是用Next.js和Tailwind CSS构建的。我按照default instructions的要求安装了它们。由于我希望自定义链接的外观,而无需对每个链接应用内联类,因此我还安装了styled-jsx-plugin-postcss,以便可以在Next.js中使用styled-jsx already bundled。
它工作得近乎完美,但由于某些原因,<style jsx>标签中应用的深色模式样式被忽略了。我使用的是class策略as documented。我怎样才能使这些风格起作用呢?
下面是来自index.js的示例代码。I also uploaded it to Codesandbox.
import { useState, useEffect } from "react";
export default function IndexPage() {
const [mounted, setMounted] = useState(false);
const handleThemeChange = (newTheme) => {
const bodyClasses = document.body.classList;
newTheme === "dark" ? bodyClasses.add("dark") : bodyClasses.remove("dark");
localStorage.theme = newTheme;
};
useEffect(() => {
const defaultTheme =
localStorage.theme ||
(window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light");
handleThemeChange(defaultTheme);
setMounted(true);
}, []);
if (!mounted) return null;
return (
<div className="dark:bg-black dark:text-white text-xl">
<ul className="cursor-pointer mb-6">
<li
onClick={() => handleThemeChange("dark")}
className="block dark:hidden"
>
Click to activate dark mode
</li>
<li
onClick={() => handleThemeChange("light")}
className="hidden dark:block"
>
Click to activate light mode
</li>
</ul>
<p>
<a href="#">This link</a> should be red in dark mode.
</p>
<style jsx>{`
a {
@apply text-green-500 dark:text-red-500;
}
`}</style>
</div>
);
}发布于 2021-06-25 03:58:49
经过深入研究,我意识到当在<style jsx>中使用dark:变体时,在最终的CSS中生成的.dark类也是作用域。所以我必须使用one-off global selector :global()来解决这个问题
<style jsx>{`
a {
@apply text-green-500;
}
:global(.dark) a {
@apply text-red-500;
}
`}</style>它需要轻微的代码重构,但我担心Tailwind无法自动绕过作用域(如果它这样做了,它甚至可能是一个意想不到的模式?)。
https://stackoverflow.com/questions/68115888
复制相似问题