【问题标题】:Spread operator not work when I use tailwindcss当我使用 tailwindcss 时,扩展运算符不起作用
【发布时间】:2021-11-04 18:34:01
【问题描述】:

你好吗?希望一切顺利!

我在 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

【问题讨论】:

    标签: css reactjs typescript next.js tailwind-css


    【解决方案1】:

    好的,所以您基本上是在第 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 也被传递,您的短路将被评估。

    【讨论】:

    • 不客气@AndresdoSantos。您应该将我的答案标记为已接受:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2018-02-19
    相关资源
    最近更新 更多