当我使用 tailwindcss 时,扩展运算符不起作用
Spread operator not work when I use tailwindcss
你好吗?希望一切顺利!
我在 Tailwindcss 中遇到了一个相当奇怪的问题,当我关闭组件的范围并获得像 ...rest
这样的道具时,className
无法正常工作,例如:
import { ButtonHTMLAttributes } from 'react';
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
title: string;
backgroundLowOpacity?: boolean;
};
export function Button({ title, backgroundLowOpacity, ...rest }: ButtonProps) {
return (
<button
{...rest}
type="button"
className={`${backgroundLowOpacity && 'bg-gray-100'}`}
>
{title}
</button>
);
}
就是这个组件,现在我想在父组件调用的时候使用className
<Button title="Sign up" className="bg-purple-500" />
但这不起作用,在这种情况下我的按钮没有颜色 purple
好的,所以你基本上是在第 13 行设置一个新的 className
道具,从而覆盖 ...rest
传播中的 className
道具。它应该是这样的:
import { ButtonHTMLAttributes } from 'react';
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
title: string;
backgroundLowOpacity?: boolean;
};
export function Button({ title, backgroundLowOpacity, className, ...rest }: ButtonProps) {
return (
<button
{...rest}
type="button"
className={`${className} ${backgroundLowOpacity && 'bg-gray-100'}`}
>
{title}
</button>
);
}
现在这样,无论您传入组件的 className
道具将首先被添加,然后如果 backgroundLowOpacity
也传入,您的短路将被评估。
你好吗?希望一切顺利!
我在 Tailwindcss 中遇到了一个相当奇怪的问题,当我关闭组件的范围并获得像 ...rest
这样的道具时,className
无法正常工作,例如:
import { ButtonHTMLAttributes } from 'react';
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
title: string;
backgroundLowOpacity?: boolean;
};
export function Button({ title, backgroundLowOpacity, ...rest }: ButtonProps) {
return (
<button
{...rest}
type="button"
className={`${backgroundLowOpacity && 'bg-gray-100'}`}
>
{title}
</button>
);
}
就是这个组件,现在我想在父组件调用的时候使用className
<Button title="Sign up" className="bg-purple-500" />
但这不起作用,在这种情况下我的按钮没有颜色 purple
好的,所以你基本上是在第 13 行设置一个新的 className
道具,从而覆盖 ...rest
传播中的 className
道具。它应该是这样的:
import { ButtonHTMLAttributes } from 'react';
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
title: string;
backgroundLowOpacity?: boolean;
};
export function Button({ title, backgroundLowOpacity, className, ...rest }: ButtonProps) {
return (
<button
{...rest}
type="button"
className={`${className} ${backgroundLowOpacity && 'bg-gray-100'}`}
>
{title}
</button>
);
}
现在这样,无论您传入组件的 className
道具将首先被添加,然后如果 backgroundLowOpacity
也传入,您的短路将被评估。