代码之家  ›  专栏  ›  技术社区  ›  jcubic

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

  •  1
  • jcubic  · 技术社区  · 8 年前

    我想这样定义jsx:

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

    我在css中使用了--length,还有一些单元格有--count,使用css伪选择器(使用counter hack)显示count。

    但typescript显示错误:

    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变量(自定义属性),或者是否可以强制样式对象上的任何类型?

    2 回复  |  直到 8 年前
        1
  •  7
  •   Matt McCutchen    8 年前

    如果你去 definition of 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

        2
  •  31
  •   ixrock    7 年前

    render(){
      var style = { "--my-css-var": 10 } as React.CSSProperties;
      return <div style={style}>...</div>
    }
    
        3
  •  4
  •   Carlos A. Cabrera    7 年前

    可以向变量添加类型断言。 即 {['--css-variable' as any]: value }

    <table style={{['--length' as any]: array.lenght}}>
       <tbody>
          <tr>{array}</tr>
       </tbody>
    </table>
    
    推荐文章