为 React + Typescript 创建 clsx 的样式规则

Create a styling rule for clsx for React + Typescript

使用这个 clsx 方法效果很好:

const getLinkClasses = (disabled: boolean) => {
  return clsx('flex whitespace-nowrap', {
    'text-gray-500': !disabled,
    'text-gray-300 cursor-not-allowed': disabled
  });
};

还有两个可选变量,一个是disabled,一个是!disabled,都是字符串,可以给上面的方法增加新的规则。我们称它们为 disabledValuenotDisabledValue.

例如,

const disabledValue = 'bg-red-100'; 
const notDisabledValue = 'bg-green-100';

为了添加这些变量,我做了以下更改:

export interface MyProps {
  disabledValue?: string;
  notDisabledValue?: string;
}

const getLinkClasses = (disabled: boolean, style: MyProps) => {
  const notDis = `text-gray-500 ${style.notDisabledValue ?? ''}`;
  const dis = `text-gray-300 cursor-not-allowed ${style.disabledValue ?? ''}`;

  return clsx('flex whitespace-nowrap', {
    notDis: !disabled,
    dis: disabled
  });
};

问题是这两个变量 notDisdis 没有被读取:

'notDis' is declared but its value is never read.ts(6133)

'notDis' is assigned a value but never used.eslint@typescript-eslint/no-unused-vars

有办法解决吗?

问题是您想使用“计算的 属性 名称”。

在 ES6+ 中是这样的:

const getLinkClasses = (disabled: boolean, style: MyProps) => {
  const notDis = `text-gray-500 ${style.notDisabledValue ?? ''}`;
  const dis = `text-gray-300 cursor-not-allowed ${style.disabledValue ?? ''}`;

  return clsx('flex whitespace-nowrap', {
    [notDis]: !disabled,
    [dis]: disabled
  });
};

参见:JavaScript set object key by variable