core中将withStyles与Typescript一起使用

core中将withStyles与Typescript一起使用

本文介绍了在新的@ material-ui/core中将withStyles与Typescript一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试将使用material-ui @ next的旧打字稿更新为新的@ material-ui/core.

I'm trying to update some of my old Typescript that used material-ui@next to the new @material-ui/core.

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

我实现了一个非常简单的组件,它只有一个道具,但是打字稿编译器在使用时会引发以下错误

I've implemented a very simple component that takes a single prop but the typescript compiler throws the following error when it is used

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

Here's the component 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);

推荐答案

classes作为属性添加到IPlaceholderProps:

Add classes to IPlaceholderProps as a property:

export interface IPlaceholderProps {
    ...
    classes
}

这篇关于在新的@ material-ui/core中将withStyles与Typescript一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:03