javascript React|将className添加到动态创建的组件

0yycz8jy  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(147)

我尝试将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,对象不可扩展

flseospp

flseospp1#

不确定它是否需要那么复杂。为什么不只是有条件地呈现图标呢?

return (
    <div
      ref={ref}
      className={`${props.className} ${styles.icon_button__wrapper}`}
    >
      <button className={styles.icon_button}>
        {
         props.icon === 'RightArrowIcon'?//or any condition here
         (
         <Icons.RightArrowIcon className={style.anyClassHere}/>
         ):
        (
         <Icons.WordIcon className={style.anyClassHere}/>
        )
        }
      </button>
      
    </div>
  )

相关问题