首页 > 解决方案 > 如何在反应中使用打字稿在div中传递样式

问题描述

这是我的代码我只想制作一个自定义组件来与打字稿做出反应,比如如果我想传递高度、宽度、边框半径和样式作为额外参数,比如如果我想要更多 css 属性然后传递 style={{display:flex}但我不能用打字稿添加这个我成功地用js写了它可以工作但不熟悉打字稿

我的界面

interface BoxProps {
    heights: React.CSSProperties;
    styles?: React.CSSProperties;
    className?: String;
    borderRadius?: React.CSSProperties
    children?: React.ReactElement<any>
}

const Box = ({ id, heights, styles, className, children }: BoxProps) => {
    const Nstyle = { ...styles,height: { heights } }
    return (
        <div
            {...id}
            style={Nstyle}
            className={CN} >
            {children}
        </div >
    );
}

请帮助样式使用 The expected type comes from property 'style' which is declared here on typetypescript 'DetailedHTMLProps, HTMLDivElement>' 显示此错误`

标签: reactjstypescript

解决方案


道具heights需要是string | number. 该className道具使用大写S字母String代替string. className={CN}应该是className={className}因为变量CN不存在。

interface BoxProps {
  heights: string | number;
  styles?: React.CSSProperties;
  className?: string;
  borderRadius?: React.CSSProperties
  children?: React.ReactElement<any>
}

const Box = ({ heights, styles, className, children }: BoxProps) => {
  const Nstyle: React.CSSProperties = { ...styles, height: heights }
  return (
      <div
        style={Nstyle}
        className={className}
      >
          {children}
      </div >
  );
}


推荐阅读