如何在 React 和打字稿中的样式属性中定义 css 变量

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

我想这样定义 jsx:

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

并且我在 CSS 中使用 --length,我也有一些单元格具有 --count 显示使用 CSS 伪选择器(使用计数器 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 变量(自定义属性)或是否有强制任何样式对象的方法?

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

link 举例说明了如何通过在 csstype 中扩充 Properties 的定义或将 属性 名称转换为 [=14= 来解决类型错误].

像这样:

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

或者没有额外的 style 变量:

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

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

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

style 转换为 any 违背了使用 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
      }
    />
  );
};
import "react";

type CustomProp = { [key in `--${string}`]: string };
declare module "react" {
  export interface CSSProperties extends CustomProp {}
}

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

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

import 'react';

declare module 'react' {
    interface CSSProperties {
        [key: `--${string}`]: string | number
    }
}

例如

<div style={{ "--value": percentage }} />

我想通过使用 document.body.style.setProperty 添加一个不同的方法,也许如果你的 css 变量会受到某些道具的影响,你可以像这样把它放在 useEffect 中:

useEffect(() => {
    document.body.style.setProperty(
      "--image-width-portrait",
      `${windowSize.width - 20}px`
    );
}, [windowSize])

稍后在您的 css 文件中,您可以这样调用它:

width: var(--image-width-portrait);