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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52005083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:36:20  来源:igfitidea点击:

How to define css variables in style attribute in React and typescript

reactjstypescriptjsxtsx

提问by jcubic

I want to define jsx like this:

我想像这样定义 jsx:

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

and I use --length in css, I also have cells that have --count that shows count using css pseudo selector (using counter hack).

我在 css 中使用了 --length,我也有使用 css 伪选择器(使用 counter hack)显示计数的 --count 单元格。

but typescript show error:

但打字稿显示错误:

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'.

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?

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

采纳答案by Matt McCutchen

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

如果您转到 的定义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
     */
}

That link gives examples of how to solve the type error by augmenting the definition of Propertiesin csstypeor casting the property name to any.

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

回答by ixrock

Like this:

像这样:

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

回答by Carlos A. Cabrera

You could add a type assertion to the variable. i.e.{['--css-variable' as any]: value }

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

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