【问题标题】:Property 'styleName' does not exist on type 'HTMLProps<HTMLDivElement>'类型“HTMLProps<HTMLDivElement>”上不存在属性“styleName”
【发布时间】:2017-08-18 10:14:36
【问题描述】:

我尝试在 typescript 中使用 react-css-modules,但我收到一条错误消息,无法将 styleName 添加到 div 元素。这是代码。

import * as Immutable from 'immutable';
import * as React from 'react';
import * as  CSSModules from 'react-css-modules';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
const styles = require<any>('./style.scss');

interface RootProps {
    data: Immutable.List<string>;
    dispatch: Dispatch<any>;
}

@CSSModules(styles)
export class Root extends React.Component<RootProps, {}>{
    render() {
        return (
            <div styleName='root'>
              Hello
            </div>
        )
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(Root);

我收到此错误消息:'Property 'styleName' does not exist on type 'HTMLProps&lt;HTMLDivElement&gt;'

还有 tsconfig

"compilerOptions": {
    "target": "es5",
    "moduleResolution": "node",
    "jsx": "react",
    "experimentalDecorators": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "allowSyntheticDefaultImports": true,
    "allowJs": true,
    "sourceMap": true,
}

【问题讨论】:

  • 你的意思是className
  • 您应该复制并粘贴代码本身,而不是创建代码的屏幕截图、裁剪和上传代码
  • 我想在 div 元素中添加一个类 'root'。但必须使用 styleName 属性
  • 为什么必须使用 styleName 属性?这不是 React 的标准属性。 css-modules 添加了吗?通常,你会使用 className 属性来添加一个类。
  • @DavinTryon 第一句中的提交者提到了他正在使用的包。如果你访问他们的 github 页面,他们会向你解释 styleName,它的好处。

标签: javascript reactjs typescript webpack react-css-modules


【解决方案1】:

使用@types/react-css-modules。

npm install --save-dev @types/react-css-modules

或者,

yarn add @types/react-css-modules --dev

【讨论】:

  • react-css-modules 似乎已被弃用。相反,他们建议尝试使用babel-plugin-react-css-modules。问题是后者没有打字。但是,即使使用babel-plugin-react-css-modules,使用答案中建议的类型也有效。我猜打字将 styleName 属性添加到 react-component 类型定义中。
【解决方案2】:

我使用 VSCode IDE 我只是更改了我的 Type Script 版本的 Work Space 而不是 IDE 版本。

【讨论】:

    【解决方案3】:

    如果有人在使用 preact 时偶然发现同样的错误,请在 /types 目录中添加 preact.d.ts 文件,内容如下:

    import preact from 'preact';
    
    declare global {
      namespace JSX {
        interface HTMLAttributes {
          styleName?: string;
        }
    
        interface SVGAttributes {
          styleName?: string;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-04
      • 2017-01-04
      • 2022-09-23
      • 2018-02-23
      • 2019-11-30
      • 2021-01-09
      • 2021-07-10
      相关资源
      最近更新 更多