[英]How to type MUI Typography props? v5
I understand what I need to do, get the type definition for Typography.variant
However I am not sure how to get these really.我明白我需要做什么,获得
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>
)
}
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
I believe this is how you can fix the type errors, both variant
and component
are not string, you can look at the Typography
type definition file here for reference.我相信这是您可以修复类型错误的方法,
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;
}
I've had the same problem, and I could fix by this way.我遇到了同样的问题,我可以通过这种方式解决。 Basing in on your code:
根据您的代码:
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>
)
}
There is another casting to the concerning element using 'as'.使用“as”对相关元素进行另一种转换。 Eg:
例如:
<Typography variant={variant as Variant } component={component as React.ElementType } onClick={onClick}>
{children}
</Typography>
This way is most used when are used flat objects, but in your case that you've used an interface the best practice is to define their properties types into the interface.这种方式在使用平面对象时最常用,但在您使用接口的情况下,最佳实践是将它们的属性类型定义到接口中。
Thumbs up!竖起大拇指!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.