添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
爱看球的机器猫  ·  Component (Java 2 ...·  1 周前    · 
会搭讪的卤蛋  ·  Factory reset ...·  1 周前    · 
紧张的热带鱼  ·  罗技 MX ...·  1 周前    · 
谦逊的楼梯  ·  Logitech Craft & MX ...·  1 周前    · 
追风的毛衣  ·  Fix CSS variable keys ...·  昨天    · 
帅气的枇杷  ·  gnustl静态还是动态 - ...·  3 月前    · 
想表白的水煮鱼  ·  .net core 3.1 json ...·  1 年前    · 
🚀 Harness AI to execute your million-dollar ideas 10x faster, with 1/10th the effort. Get Started

Fix CSS variable keys in style attributes in React and Typescript

2/22/2021

Josh Comeau has a wonderful article about using CSS variables in style attributes in React props that has changed the way I write CSS in React ( link ).

Unfortunately, when using TypeScript, this method leads to a build error.

The Error

TS2326: Types of property 'style' are incompatible.
Type '{ "--color": string; }' is not assignable to type 'CSSProperties'.
Object literal may only specify known properties, and '"--color"' does not exist in type 'CSSProperties'.

How to Fix it

There are two ways to fix the build error:

  • cast the style object to React.CSSProperties
  • create an interface that extends React.CSSProperties
  • Cast the style object to React.CSSProperties

    The part to note here is that the style object is followed by as React.CSSProperties:

     <StyledComponent style={{ "--color": colorValue } as React.CSSProperties}>
     {/* details... */}
     </StyledComponent>
    

    The downside of casting is that it will allow any key arbitrarily. If you want to be explicit about what keys are available, try the next method, Extending CSSProperties.

    Create an interface that extends React.CSSProperties

    Extending CSSProperties has the advantage of allowing you to say which keys are acceptable:

    import React, { CSSProperties } from 'react';