英文:
Why do tailwind breakpoints not work in this case with Next.js?
问题
// 代码部分不要翻译
function HideUnderBreakpoint({
breakpoint,
children,
}: {
breakpoint: "xs" | "sm" | "md" | "xl";
children: React.ReactNode;
}) {
return <div className={`block max-${breakpoint}:hidden`}>{children}</div>;
}
然而,在Next.js中使用时,当在浏览器中检查时,类max-something:hidden没有CSS规则。
我注意到修改返回值为以下内容可以生成预期的类 - 尽管忽略了breakpoint属性:
return <div className={`block max-md:hidden`}>{children}</div>
但现在您可以创建多个这样的组件,并有条件地渲染相关的组件 - 类会按预期工作。
这对我来说很奇怪,因为组件生命周期中breakpoint属性从未改变。我希望Next.js能够“正常工作”。我不确定问题是否特定于tailwind、postcss、Next.js甚至是项目中还存在的react-jss。
为什么这个能够工作而另一个不能工作?
<details>
<summary>英文:</summary>
I have a component that should hide an element if the viewport is below the md breakpoint. It looks as follows:
```JavaScript
function HideUnderBreakpoint({
breakpoint,
children,
}: {
breakpoint: "xs" | "sm" | "md" | "xl";
children: React.ReactNode;
}) {
return <div className={`block max-${breakpoint}:hidden`}>{children}</div>;
}
However, when I use this in Next.js, there will be no CSS rules for the class max-something:hidden when inspecting it in the browser.
I have noted that modifying the return value to this generates the class as intended - admittedly ignoring the breakpoint prop:
return <div className={`block max-md:hidden`}>{children}</div>;
But you can now create several of these components and conditionally render the relevant one - and the classes will work as intended.
This seems strange to me, since the breakpoint prop never changes during the lifetime of the component. I would expect Next.js to "just work". I am not certain if the issue is specific to tailwind, postcss, Next.js or even react-jss, which is also present in the project.
Why does this work and the other one does not work?
答案1
得分: 3
Tailwind 使用正则表达式来查找类名,因此它们需要作为源代码中的不间断字符串存在。由于这个原因,你不能像你尝试的那样使用字符串内插,因为 Tailwind 将无法找到该类名。
你可以做的是将你的 props 映射到静态类名:
function HideUnderBreakpoint({
breakpoint,
children,
}: {
breakpoint: "xs" | "sm" | "md" | "xl";
children: React.ReactNode;
}) {
const sizeVariants = {
xs: 'max-xs:hidden',
sm: 'max-sm:hidden',
md: 'max-md:hidden',
xl: 'max-xl:hidden',
}
return <div className={`block ${sizeVariants[breakpoint]}`}>{children}</div>;
}
英文:
Tailwind uses regex to find class names, and because of this they need to exist as unbroken strings in your source code. A consequence of this is you cannot use string interpolation the way you're trying to do, as Tailwind will not be able to find the class name.
What you can do instead is map your props to static class names:
function HideUnderBreakpoint({
breakpoint,
children,
}: {
breakpoint: "xs" | "sm" | "md" | "xl";
children: React.ReactNode;
}) {
const sizeVariants = {
xs: 'max-xs:hidden',
sm: 'max-sm:hidden',
md: 'max-md:hidden',
xl: 'max-xl:hidden',
}
return <div className={`block ${sizeVariants[breakpoint]}`}>{children}</div>;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论