我正在尝试将一些使用material-ui@next的旧Typescript更新为新的@material-ui/core。
Typescript Version: 2.8.3
@material-ui/core: 1.1.0
我已经实现了一个非常简单的组件,它需要一个道具,但是打字稿编译器在使用它时会抛出以下错误
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);
我在尝试为我的样式创建类型时也遇到了一些问题,因此如果 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>>
如果您找到更好、更短的方法来做同样的事情,请告诉我:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)