如何在React和TypeScript的style属性中定义CSS变量

jcu*_*bic 9 jsx typescript reactjs tsx

我想这样定义jsx:

<table style={{'--length': array.lenght}}>
   <tbody>
      <tr>{array}</tr>
   </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

并且我在CSS中使用--length,也有一些单元格具有--count,它们使用css伪选择器(使用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'.
Run Code Online (Sandbox Code Playgroud)

是否可以更改样式属性的类型以接受CSS变量(自定义属性),或者是否可以对样式对象进行强制?

min*_*lid 65

您可以简单地将使用字符串模板的模块声明合并放在文件顶部或任何 .d.ts 文件中,然后您将能够使用任何 CSS 变量,只要它以“--”开头,即字符串或数字

import 'react';

declare module 'react' {
    interface CSSProperties {
        [key: `--${string}`]: string | number
    }
}
Run Code Online (Sandbox Code Playgroud)

例如

<div style={{ "--value": percentage }} />
Run Code Online (Sandbox Code Playgroud)

  • 记得将 `import 'react'` 放在顶部! (2认同)

Car*_*era 17

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

<table style={{['--length' as any]: array.lenght}}>
   <tbody>
      <tr>{array}</tr>
   </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

  • 抑制打字稿错误并不是最好的解决方案 (10认同)

ixr*_*ock 15

像这样:

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

  • 我认为这是我在接受答案的示例之后得出的结论,但是直接答案总是更好。 (2认同)

HaN*_*riX 15

尝试:

<table style={{['--length' as string]: array.lenght}}>
  ...
</table>
Run Code Online (Sandbox Code Playgroud)


Ben*_*uer 12

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

import React, {CSSProperties} from 'react';

export interface MyCustomCSS extends CSSProperties {
  '--length': number;
}
Run Code Online (Sandbox Code Playgroud)

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

使用MyCustomCSS看起来像这样:

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

  • TS 4.4 支持模板文字类型,因此可以编写类似的内容,而不是显式指定所有自定义变量: ```[key: `--${string}`]: string | 数;```。一行:```type MyCustomCSS = CSSProperties &amp; Record&lt;`--${string}`,number | 字符串&gt;;``` (11认同)

Mat*_*hen 6

如果转到的定义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
     */
}
Run Code Online (Sandbox Code Playgroud)

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

  • 刚刚测试了第二个例子,它看起来更简单,而且有效。 (2认同)
  • 链接已经过时了,如果它之前有用的话,它很可能会指向提交而不是主控。 (2认同)

小智 5

import "react";

type CustomProp = { [key in `--${string}`]: string };
declare module "react" {
  export interface CSSProperties extends CustomProp {}
}
Run Code Online (Sandbox Code Playgroud)

将其放入您的 global.d.ts 文件中

  • @jcubic React 开发者不同意你的观点,正如 /sf/answers/3640923821/ 中引用的评论所证明的那样 (2认同)