【问题标题】:Material ui wrapper - reuse typescript types for a given propMaterial ui wrapper - 为给定的 prop 重用 typescript 类型
【发布时间】:2020-10-07 22:37:49
【问题描述】:

首先很抱歉,如果之前回答过这个问题,我找不到它。

由于某些原因,在我现在正在工作的应用程序中,我们有一个用于一些 material-ui 组件的包装器。例如,我有一个 MyCompanyButton,它是 material-ui Button 组件的包装器。

其实很简单,像这样:

const MyCompanyButton: React.FC<MyCompanyButtonProps> = (props): React.ReactElement => {
  const { label, color, type } = props;

  return (
    <Button color={color} type={type}>
      {label}
    </Button>
  );
};

问题在于道具的类型。

我的第一次尝试是这样定义它们:

type MyCompanyButtonProps = {
  label: string;
  color: string;
  type: string;
};

但是当我尝试像这样使用我的组件时:

<MyCompanyButton color="primary" type="submit" label="Send" />

我收到以下错误:

类型“字符串”不可分配给类型“默认”| “继承” | “主要” | “次要” |不明确的'。 TS2769

我了解错误,但我不知道如何修复它。我想重用 material-ui 类型,但我找不到它们。我知道在当前版本中它们是内置在核心包中的,但我不明白如何找到“颜色”类型并将其应用于我的颜色属性。

到目前为止,我所做的是从错误中获取类型定义并将其应用于我的道具:

颜色:“默认”| “继承” | “主要” | “次要” |未定义;

但是,我认为这不是这样做的方法,因为如果库中的类型发生变化,我也需要在此处进行更改。

我希望有人可以帮助我。

谢谢!

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

    由于您这样做是为了扩展 Button 组件,因为 label 不是 MUI Button 属性的一部分,因此您可以使用 MUI ButtonProps 类型扩展您的 MyCompanyButtonProps 类型定义,如下所示:

    import { Button, ButtonProps } from '@material-ui/core';
    
    interface MyCompanyButtonProps extends ButtonProps {
      label: string;
    }
    
    export const MyCompanyButton: React.FC<MyCompanyButtonProps> = (props): React.ReactElement => {
      const { label, color, type } = props;
    
      return (
        <Button color={color} type={type}>
          {label}
        </Button>
      );
    };
    

    一般而言,使用 Material UI 库,可以从与组件相同的位置导入组件 props,在组件名称后面加上 Props。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-03
      • 2018-09-21
      • 2020-11-03
      • 2018-03-01
      • 2016-09-09
      • 2022-08-20
      • 2019-10-06
      • 1970-01-01
      相关资源
      最近更新 更多