【问题标题】:Create a styling rule for clsx for React + Typescript为 React + Typescript 的 clsx 创建样式规则
【发布时间】:2022-01-17 06:08:00
【问题描述】:

拥有这个运行良好的 clsx 方法:

const getLinkClasses = (disabled: boolean) => {
  return clsx('flex whitespace-nowrap', {
    'text-gray-500': !disabled,
    'text-gray-300 cursor-not-allowed': 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' 被声明,但它的值永远不会被读取。ts(6133)

'notDis' 被赋值但从不 used.eslint@typescript-eslint/no-unused-vars

有办法解决吗?

【问题讨论】:

标签: javascript css typescript tailwind-css clsx


【解决方案1】:

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

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2020-10-23
    • 2020-01-16
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多