reactjs - 打字稿中组件中的额外可选类名
问题描述
我正在使用类名向 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)
解决方案
你className
被用作属性名称,即使它可能未定义。请注意,可选项string
实际上是string | undefined
. 我会使用对象传播来完成条件性。
类名函数的新参数:
{
[styles.small]: small,
...(typeof className === 'string' ?
{ [className]: true } :
{}
)
}
推荐阅读
- webpack - Webpack 开发服务器热重载不适用于 SCSS 和多个条目
- python - Pandas - 从具有出现次数的可迭代对象中获取假人
- android - PdfRenderer 错误:java.io.IOException:无法创建文档。错误:3
- ios - 未找到“ConnectyCube/ConnectyCube.h”文件
- java - 如何使用java从子jsonnode获取值
- swift - 如何将按钮添加到 CollectionView 的末尾(不在最后一个单元格中)?
- ios - 在保持底部填充的同时更改中心 Google 地图位置
- python - Python为mysql创建动态选择语句
- java-8 - 将 Stream 转换为 IntStream
- powerbi - 在 Power BI 中评论报表