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

5q4ezhmt  于 2022-12-03  发布在  React
关注(0)|答案(8)|浏览(104)

我想这样定义jsx:

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

我在CSS中使用了--length,我还有一些单元格使用了--count,它使用CSS伪选择器显示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变量(自定义属性),或者是否有办法强制样式对象接受CSS变量?

xpcnnkqh

xpcnnkqh1#

您可以将类型Assert添加到变量中。* 即 * {['--css-variable' as any]: value }

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

omvjsjqw2#

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
      }
    />
  );
};
mitkmikd

mitkmikd3#

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

import 'react';

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

例如,

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

uubf1zoe4#

import "react";

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

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

ztigrdn8

ztigrdn85#

我想通过使用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);
ruarlubt

ruarlubt6#

尝试:

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

xdyibdwo7#

就像这样:

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} />
}
jgzswidk

jgzswidk8#

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

该链接提供了一些示例,说明如何通过扩充csstypeProperties的定义或将属性名转换为any来解决类型错误。

相关问题