繁体   English   中英

如何打字 MUI 排版道具? v5

[英]How to type MUI Typography props? v5

我明白我需要做什么,获得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

我相信这是您可以修复类型错误的方法, variantcomponent都不是字符串,您可以在此处查看Typography类型定义文件以供参考。

import Typography, { TypographyTypeMap } from "@mui/material/Typography";

interface TextProps {
  variant?: TypographyTypeMap["props"]["variant"];
  component?: React.ElementType;
  onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
}

代码沙盒演示

我遇到了同样的问题,我可以通过这种方式解决。 根据您的代码:

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>

这种方式在使用平面对象时最常用,但在您使用接口的情况下,最佳实践是将它们的属性类型定义到接口中。

竖起大拇指!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM