首页 > 解决方案 > 打字稿中组件中的额外可选类名

问题描述

我正在使用类名向 React 组件添加许多类。在我的按钮中,如果我愿意,我希望有机会向组件添加一个类,它应该是可选的。

但我得到一个类型错误,见附图在此处输入图像描述

我怎样才能摆脱错误?

按钮代码

import classnames from "classnames";
import styles from "./button.module.css";

interface ButtonProps {
    children: JSX.Element;
    onClick: () => void;
    small?: boolean;
    className?: string;
}

function Button({ onClick, children, small, className }: ButtonProps) {
    return (
        <button
            className={classnames(styles.button, {
                [styles.small]: small,
                [className]: !!className,
            })}
            onClick={onClick}
        >
            {children}
        </button>
    );
}

export default Button;

和错误:

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)

标签: reactjstypescriptclass-names

解决方案


className被用作属性名称,即使它可能未定义。请注意,可选项string实际上是string | undefined. 我会使用对象传播来完成条件性。

类名函数的新参数:

{
  [styles.small]: small,
  ...(typeof className === 'string' ?
    { [className]: true } :
    {}
  )
}

推荐阅读