我明白我需要做什么,得到Typography.variant的类型定义,但是我不知道如何真正得到这些。
interface TextProps {
variant?: string
component?: string
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void
}
export const Text = ({ children, variant = 'body1', component = 'body1', onClick }: PropsWithChildren<TextProps>) => {
return (
<Typography variant={variant} component={component} onClick={onClick}>
{children}
</Typography>
)
}TS误差
No overload matches this call.
Overload 2 of 2, '(props: DefaultComponentProps<TypographyTypeMap<{}, "span">>): Element', gave the following error.
Type 'string' is not assignable to type '"button" | "caption" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "inherit" | "overline" | "body1" | "subtitle1" | "subtitle2" | "body2" | undefined'. TS2769发布于 2021-10-14 16:14:43
我相信这就是如何修复类型错误的方法,variant和component都不是字符串,您可以查看Typography类型定义文件这里以供参考。
import Typography, { TypographyTypeMap } from "@mui/material/Typography";
interface TextProps {
variant?: TypographyTypeMap["props"]["variant"];
component?: React.ElementType;
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
}
发布于 2021-11-06 23:09:56
我也有过同样的问题,我可以用这种方法来解决。根据您的代码:
import React from 'react';
import { Variant } from '@mui/material/styles/createTypography';
interface TextProps {
variant?: Variant
component?: React.ElementType
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void
}
export const Text = ({ children, variant = 'body1', component = 'body1', onClick }: PropsWithChildren<TextProps>) => {
return (
<Typography variant={variant} component={component} onClick={onClick}>
{children}
</Typography>
)
}使用“as”对有关元素进行另一次转换。例:
<Typography variant={variant as Variant } component={component as React.ElementType } onClick={onClick}>
{children}
</Typography>这种方法在使用平面对象时使用最多,但在您使用了接口的情况下,最佳实践是将它们的属性类型定义到接口中。
行,可以!
https://stackoverflow.com/questions/69573929
复制相似问题