如何在 React 和 typescript 的样式属性中定义 css 变量

新手上路,请多包涵

我想这样定义jsx:

 <table style={{'--length': array.lenght}}>
   <tbody>
      <tr>{array}</tr>
   </tbody>
</table>

我在 CSS 中使用 –length,我也有具有 –count 的单元格,它使用 CSS 伪选择器(使用计数器 hack)显示计数。

但打字稿抛出错误:

 TS2326: Types of property 'style' are incompatible.
  Type '{ '--length': number; }' is not assignable to type 'CSSProperties'.
    Object literal may only specify known properties, and ''--length'' does not exist in type 'CSSProperties'.

是否可以更改样式属性的类型以接受 CSS 变量(自定义属性),或者有没有办法强制任何样式对象?

原文由 jcubic 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 4.7k
2 个回答

如果你去 定义 CSSProperties ,你会看到:

 export interface CSSProperties extends CSS.Properties<string | number> {
    /**
     * The index signature was removed to enable closed typing for style
     * using CSSType. You're able to use type assertion or module augmentation
     * to add properties or an index signature of your own.
     *
     * For examples and more information, visit:
     * https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors
     */
}

该链接提供了如何通过在 Properties 中增加 csstype 的定义或将属性名称转换为 any 来解决类型错误的示例。

原文由 Matt McCutchen 发布,翻译遵循 CC BY-SA 4.0 许可协议

像这样:

 function Component() {
  const style = { "--my-css-var": 10 } as React.CSSProperties;
  return <div style={style}>...</div>
}

或者没有额外的 style 变量:

 function Component() {
  return <div style={{ "--my-css-var": 10 } as React.CSSProperties} />
}

原文由 ixrock 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进