我尝试将className属性添加到新创建的组件中,如下所示:
const component = <Icons.RightArrowIcon /> // I want to add a className to this component
// Then...
// ...
return (
<>{component}</>
)
我写了下面的代码:
type IconButtonProps = {
icon: 'RightArrowIcon' | 'WordIcon';
className?: string;
};
// eslint-disable-next-line react/display-name
const IconButton = React.forwardRef<any, IconButtonProps>((props, ref) => {
const getIcon = () => {
let icon: React.ReactNode | null = null
if (props.icon === 'RightArrowIcon') {
icon = <Icons.RightArrowIcon />
} else if (props.icon === 'WordIcon') {
icon = <Icons.WordIcon />
}
// This is what I thought it would be
if (icon !== null) { icon.props.className = styles.icon_button__icon }
return icon
}
return (
<div
ref={ref}
className={`${props.className} ${styles.icon_button__wrapper}`}
>
<button className={styles.icon_button}>
{getIcon()}
</button>
</div>
)
})
export default IconButton
但我得到了这个错误:
TypeError:无法添加属性className,对象不可扩展
1条答案
按热度按时间flseospp1#
不确定它是否需要那么复杂。为什么不只是有条件地呈现图标呢?