【问题标题】:Using withStyles with Typescript in the new @material-ui/core在新的 @material-ui/core 中使用 withStyles 和 Typescript
【发布时间】:2018-11-06 14:13:50
【问题描述】:

我正在尝试将一些使用 material-ui@next 的旧 Typescript 更新为新的 @material-ui/core。

Typescript Version: 2.8.3
@material-ui/core: 1.1.0

我已经实现了一个非常简单的组件,它采用单个 prop,但是 typescript 编译器在使用时会抛出以下错误

src/App.tsx(21,26): error TS2322: Type '{ classes: true; imageUrl: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Placeholder> & Readonly<{ children?: ReactNode; }>...'.
  Type '{ classes: true; imageUrl: string; }' is not assignable to type 'Readonly<PROPS_WITH_STYLES>'.
    Types of property 'classes' are incompatible.
      Type 'true' is not assignable to type 'Record<"root", string>'.

这是组件 Placeholder.tsx

import * as React from "react";
import { StyleRulesCallback, WithStyles, withStyles, StyledComponentProps } from "@material-ui/core";

export interface IPlaceholderProps {
    imageUrl: string;
}

export const STYLES: StyleRulesCallback<"root"> = theme => ({
    root: {
        display: "flex",
        justifyContent: "center",
        alignItems: "center"
    }
});

export type PROPS_WITH_STYLES = IPlaceholderProps & WithStyles<"root">;

export class Placeholder extends React.Component<PROPS_WITH_STYLES, {}> {
    render(){
        return <div className={this.props.classes.root}>
            <img src={this.props.imageUrl}/>
        </div>;
    }
}

export default withStyles(STYLES, { withTheme: true })<PROPS_WITH_STYLES>(Placeholder);

【问题讨论】:

标签: reactjs typescript material-ui


【解决方案1】:

classes 作为属性添加到IPlaceholderProps:

export interface IPlaceholderProps {
    ...
    classes
}

【讨论】:

  • 确实可以编译,谢谢。不过,有点感觉 withStyles 不值得所有这些样板。
【解决方案2】:

我在尝试为我的样式创建类型时也遇到了一些问题,所以如果 Material-ui 中的 WithStyles 不起作用,如何正确键入您的样式

const styles = (props) => ({
  container: {
    display: 'flex',
  }      
})
 

type Props = {
  blabla: string;
  classes: Record<keyof ReturnType<typeof styles>, string>
}

您可能还想为此创建一个实用类型

const styles = (props) => ({
  container: {
    display: 'flex',
  }       
})
 

type MaterialStyle<S> = { 
  classes: Record<keyof S, string>
}


type Props = {
  blabla: string;
} & MaterialStyle<ReturnType<typeof styles>>

如果你找到更好更短的方法来做同样的事情,请告诉我:)

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多