[英]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,它们是字符串,可以为上述方法添加新规则。 我们称它们为disabledValue
和notDisabledValue
。
例如,
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
});
};
问题是这两个变量notDis
和dis
没有被读取:
'notDis' 已声明,但它的值永远不会被读取。ts(6133)
'notDis' 被赋值但从未使用过。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
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.