在新的 @material-ui/core 中使用 withStyles 和 Typescript

Bli*_*ers 6 typescript reactjs material-ui

我正在尝试更新我的一些旧打字稿,这些打字稿在新的 @material-ui/core 旁边使用了 material-ui@。

Typescript Version: 2.8.3
@material-ui/core: 1.1.0
Run Code Online (Sandbox Code Playgroud)

我已经实现了一个非常简单的组件,它只需要一个 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>'.
Run Code Online (Sandbox Code Playgroud)

这是组件 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);
Run Code Online (Sandbox Code Playgroud)

Ani*_*nyi 2

添加classes到 IPlaceholderProps 作为属性:

export interface IPlaceholderProps {
    ...
    classes
}
Run Code Online (Sandbox Code Playgroud)

  • 这确实可以编译,谢谢。不过,有点感觉 withStyles 不值得所有这些样板。 (5认同)