簡體   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