如何在React和TypeScript的style属性中定义css变量 [英] How to define css variables in style attribute in React and typescript

查看:201
本文介绍了如何在React和TypeScript的style属性中定义css变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样定义jsx:

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

并且我在CSS中使用--length,也有一些单元格具有--count,它们使用css伪选择器(使用计数器破解)显示计数.

and I use --length in css, I also have cells that have --count that shows count using css pseudo selector (using counter 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变量(自定义属性),或者是否可以对样式对象强制执行任何操作?

is it possible to change type of style attribute to accept css variable (custom properties) or is there a way to force any on style object?

推荐答案

如果转到

If you go to the definition of CSSProperties, you'll see:

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
     */
}

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

That link gives examples of how to solve the type error by augmenting the definition of Properties in csstype or casting the property name to any.

这篇关于如何在React和TypeScript的style属性中定义css变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆