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

时间:2018-05-28 03:16:12

标签: reactjs typescript material-ui

我正在尝试更新我在旧的@ material-ui / core旁边使用material-ui @的旧的Typescript。

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);

2 个答案:

答案 0 :(得分:2)

classes作为属性添加到IPlaceholderProps:

export interface IPlaceholderProps {
    ...
    classes
}

答案 1 :(得分:0)

在尝试为我的样式创建类型时,我也遇到了一些问题,因此在这里,如果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>>

让我知道您是否找到一种更好,更短的方法来做同样的事情:)