J. *_*ers 4 typescript reactjs typescript-typings typescript-types react-props
我正在使用TypeScript编写React应用程序。我将material-ui用于组件。我正在为material-ui的Button组件编写自定义包装。看起来像这样:
import MUIButton, { ButtonProps } from "@material-ui/core/Button";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import classNames from "classnames";
import React, { PureComponent } from "react";
import styles from "./styles";
export interface OwnProps {
color: "primary" | "danger" | "warning" | "transparent";
size: "sm" | "lg";
}
export interface Props
extends WithStyles<typeof styles>,
OwnProps,
ButtonProps {}
export class Button extends PureComponent<Props> {
render() {
const { color, size, classes, children, ...rest } = this.props;
const btnClasses = classNames({
[classes.button]: true,
[classes[size]]: size,
[classes[color]]: color
});
return (
<MUIButton {...rest} className={btnClasses}>
{children}
</MUIButton>
);
}
}
export default withStyles(styles)(Button);
Run Code Online (Sandbox Code Playgroud)
问题在于,此处的Props定义会引发错误消息:
Named property 'color' of types 'OwnProps' and 'ButtonProps' are not identical.
[ts]
Interface 'Props' cannot simultaneously extend types 'OwnProps' and 'ButtonProps'.
Named property 'size' of types 'OwnProps' and 'ButtonProps' are not identical.
Named property 'color' of types 'OwnProps' and 'ButtonProps' are not identical.
[ts]
Interface 'Props' cannot simultaneously extend types 'OwnProps' and 'ButtonProps'.
Named property 'size' of types 'OwnProps' and 'ButtonProps' are not identical.
Run Code Online (Sandbox Code Playgroud)
如果我改为写此错误消失:
export class Button extends PureComponent<Props & ButtonProps> {
Run Code Online (Sandbox Code Playgroud)
但是,当使用按钮时,道具的颜色和大小会引发错误:
The expected type comes from property 'color' which is declared here on type 'IntrinsicAttributes & Pick<Props & ButtonProps, ...
Run Code Online (Sandbox Code Playgroud)
我如何OwnProps像往常一样正确地告诉组件它具有我定义的道具()以及来自Button的道具?
import { ButtonProps } from "@material-ui/core/Button";
export type OwnProps = Omit<ButtonProps, "color" | "size"> & {
color: "primary" | "danger" | "warning" | "transparent";
size: "sm" | "lg";
}
class MyButton extends React.Component<OwnProps> {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1585 次 |
| 最近记录: |