簡體   English   中英

TypeScript 錯誤:類型“字符串”不可分配給排版類型

[英]TypeScript error: Type 'string' is not assignable to type for Typography

我正在嘗試將 material-ui 中的 Typography 組件與 TypeScript 一起使用,但我收到了這個奇怪的錯誤

TypeScript error: Type 'string' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLElement>, any> | FunctionComponent<HTMLAttributes<HTMLElement>> | undefined'.  TS2322

     8 | }
     9 | export default ({ text, date }: Props) => (
  > 10 |   <Typography component="p" gutterBottom>
       |               ^
    11 |     {text && <span>{text}:&nbsp;</span>}
    12 |     <FormattedDate value={date} />
    13 |     &nbsp;

這是我的組件的樣子

import React from 'react';
import { FormattedDate, FormattedTime } from 'react-intl';
import Typography from '@material-ui/core/Typography';

interface Props {
  date: Date;
  text?: string;
}
export default ({ text, date }: Props) => (
  <Typography component="p" gutterBottom>
    {text && <span>{text}:&nbsp;</span>}
    <FormattedDate value={date} />
    &nbsp;
    <FormattedTime value={date} />
  </Typography>
);

我無法理解為什么"p"不是component道具的可接受值。 我用"h1"和 " h2"嘗試了同樣的方法失敗了,顯然,官方演示也使用了字符串。

有什么我遺漏的嗎?,我不想用// @ts-ignore它,但想解決這個問題。

根據 Material UI 提供的排版參考文檔( https://material-ui.com/api/typography/

{ h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', subtitle1: 'h6', subtitle2: 'h6', body1: 'p', body2: 'p',}

variantMapping具有這些映射,因此如果您想使用<p>標簽,您可以使用變體類型作為 body1 或 body2 而不是組件屬性。

我有這個,因為我更新到material-ui/core@4.6.0typescript@3.7.2

我設法通過使用component={'div' as any}來消除錯誤,因此我將其發布為臨時答案,但我確實認為必須有更好的解決方案。

在 2021 年有這個問題,問題是我正在針對HTMLAttributes傳播輸入的InputBase ,而我應該正確傳播InputBaseProps

在我的例子中,它與輸入相關,但可以為每個組件復制相同的內容:只要您使用材質 UI 組件,您應該提供它要求的屬性,並在使用/擴展它們時正確設置正確的道具類型。

給出錯誤的示例:

import { HTMLAttributes } from 'react';

import InputBase from '@material-ui/core/InputBase';

import inputStyle from 'Input.module.scss';

export interface InputProps extends HTMLAttributes<HTMLInputElement> {
  
}

export function Input(props: InputProps) {
  const { ...rest } = props;

  return (
    <InputBase
      fullWidth={true}
      className={[inputStyle.input].join(' ')}
      color='primary'
      {...rest}
    />
  );
}

(在這種情況下, color出現錯誤)

正確的方法:

import InputBase, { InputBaseProps } from '@material-ui/core/InputBase';

import inputStyle from 'Input.module.scss';

export interface InputProps extends InputBaseProps {
  
}

export function Input(props: InputProps) {
  const { ...rest } = props;

  return (
    <InputBase
      fullWidth={true}
      className={[inputStyle.input].join(' ')}
      color='primary'
      {...rest}
    />
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM