【问题标题】:Typescript React; How to give type to JSS classes object打字稿反应;如何为 JSS 类对象指定类型
【发布时间】:2021-12-30 07:53:18
【问题描述】:

我的反应代码:

import React from 'react';
import withStyles from "react-jss";

const styles = {
      box: {
          border: "2px solid #000"
      }
  };

interface ComponentProps {}

class Welcome extends React.Component<ComponentProps> {
    render() {
      const {classes, children} = this.props;
      return(<div className={classes.box}></div>);
    }
  }

  export default withStyles(styles)(Welcome);

const {classes, children} = this.props; 中,classes 显示此错误:

Property 'classes' does not exist on type 'Readonly<ComponentProps> & Readonly<{ children?: ReactNode; }>'.ts(2339)

摆脱这个错误的唯一方法似乎就是这样做;

interface ComponentProps {
    classes:any
  }

但是使用any 在语义上是错误的。我应该给 classes 什么类型,或者这不是 jss 在 typescript-react 中的使用方式吗?
(JSS如何与TS一起使用:github.com/cssinjs/jss/blob/master/docs/react-jss-ts.md(仅功能组件))

【问题讨论】:

    标签: reactjs typescript react-typescript jss


    【解决方案1】:

    看起来你正在使用withStyles,它来自于材料 ui。 Material UI 有CSSProperties,这是你需要的。

    import { CSSProperties } from "@material-ui/styles";
    
    interface ComponentProps {
      classes: CSSProperties;
    }
    

    对于非 MUI 解决方案,请查看CSSType

    import CSS from "csstype";
    
    interface ComponentProps {
      classes: { [key: string]: CSS };
    }
    

    【讨论】:

    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2017-06-24
    • 2021-08-05
    • 2017-01-16
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多