【问题标题】:How to add CSS new 'content-visibility' property to a React class component that uses Typescript and SCSS?如何将 CSS 新的“内容可见性”属性添加到使用 Typescript 和 SCSS 的 React 类组件?
【发布时间】:2021-01-12 00:13:22
【问题描述】:

我正在尝试添加这个新发布的样式属性 - (这是一个新的 css 属性 - 你可以阅读它here

content-visibility: auto;
contain-intrinsic-size: 1000px;

到一个 div 包装一些内容,但得到属性未知的错误。 到目前为止,我已经尝试过:

  1. 将其添加到正确类下的 scss 中,如下所示:
.capWrapper {
  width: 100%;
  margin-bottom: 108px;
  margin-top: 71px;

  content-visibility: auto;
  contain-intrinsic-size: 1000px; 
}

但出现错误: Unknown property: 'content-visibility'scss(unknownProperties)

  1. 将其作为样式对象直接添加到元素中:
render() {
    
    const contentVisibilityStyle = {
      contentVisibility: 'auto',
      containIntrinsicSize: '1000px' 
    } as React.CSSProperties;

    return (
      <div className={classes["capWrapper"]} style={{contentVisibilityStyle}}>
        some content
      </div> 

但是得到这个错误:

Type '{ contentVisibilityStyle: React.CSSProperties; }' is not assignable to type 'CSSProperties'.
  Object literal may only specify known properties, and 'contentVisibilityStyle' does not exist in type 'CSSProperties'.ts(2322)
index.d.ts(1437, 9): The expected type comes from property 'style' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>'

非常感谢任何如何正确实现此属性的想法。

【问题讨论】:

  • 选项 1 中的错误是什么?你的 SCSS 编译器?或者它只是来自你的 linter 的警告或其他什么?

标签: css reactjs typescript


【解决方案1】:

发生的事情是 React+Typescript 无法识别新的 CSS 属性。 构建失败是因为 React 说“我不知道这是什么并且无法处理它”。 可能是因为您使用的 TS 版本不支持它们,或者它们太新以至于 TS 还没有添加对它们的支持。

你有几个选择:

  1. 您可以自己定义这些新的 CSS 属性,并通过在 d.ts 文件中进行扩展来扩展对 TS 的理解。 这将使 TS 理解它们并使构建失败。这也将在您未来的工作中为您提供智能感知。

  2. 您可以通过将它们添加到一个简单的 CSS 文件中并加载应用程序范围的 ot 来绕过所有这些。例如直接在您的 index.html 中。这将使 Typescript 编译器或反应或任何其他框架只是忽略它(因为他们不知道它)

我还建议检查是否有人发布了一些 NPM 包,为 Typescript 添加了对这些新 CSS 属性的支持。

第一个解决方案更像是“自己动手”。第二种方法比较老套,但肯定会奏效。

祝你好运。

【讨论】:

    【解决方案2】:

    您创建一个css.d.ts 文件:

    import * as CSS from "csstype";
    
    declare module "csstype" {
      interface Properties {
        contentVisibility: "visible" | "auto" | "hidden";
      }
    }
    

    这是因为 @types/react 依赖于 csstype 的 css。

    https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-12
      • 2021-06-29
      • 1970-01-01
      • 2020-11-30
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多