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

IT技术 reactjs typescript jsx tsx
2021-05-09 10:01:19

我想像这样定义 jsx:

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

我在 CSS 中使用 --length,我也有使用 CSS 伪选择器(使用计数器 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 变量(自定义属性),或者有没有办法强制任何样式对象?

4个回答

像这样:

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

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

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

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

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

强制转换styletoany违背了使用 TypeScript 的全部目的,因此我建议React.CSSProperties使用您的自定义属性集进行扩展

import React, {CSSProperties} from 'react';

export interface MyCustomCSS extends CSSProperties {
  '--length': number;
}

通过扩展React.CSSProperties,您将使 TypeScript 的属性检查保持活动状态,并且您将被允许使用您的自定义--length属性。

使用MyCustomCSS看起来像这样:

const MyComponent: React.FC = (): JSX.Element => {
  return (
    <input
      style={
        {
          '--length': 300,
        } as MyCustomCSS
      }
    />
  );
};