首页 > 解决方案 > 在 props 接口中访问 React 类型

问题描述

我有一个像这样的功能组件:

import React, { memo } from 'react';

import {
  ButtonStyled,
  LinkStyled,
  Text,
} from './index.style';


export interface Props {
  buttonType?: string;
  handleClick?: () => void;
  href?: string;
  invertColors?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
  text: string;
  variant?: 'dark' | 'light';
}

const defaultProps = {
  buttonType: 'button',
  handleClick: null,
  href: null,
  invertColors: false,
  isDisabled: false,
  isLoading: false,
  variant: 'dark',
};


const Button = ({
  buttonType,
  handleClick,
  href,
  isDisabled,
  isLoading,
  text,
  variant,
}: Props) => {
  if (href) {
    return (
      <LinkStyled
        href={href}
        isDisabled={isDisabled}
        isLoading={isLoading}
        variant={variant}
      >
        <Text isLoading={isLoading}>
          {text}
        </Text>
      </LinkStyled>
    );
  }

  return (
    <ButtonStyled
      disabled={isDisabled}
      isDisabled={isDisabled}
      isLoading={isLoading}
      onClick={handleClick}
      type={buttonType}
      variant={variant}
    >
      <Text isLoading={isLoading}>
        {text}
      </Text>
    </ButtonStyled>
  );
};


Button.defaultProps = defaultProps;

export default memo(Button);

此文件中有一个 Typescript 错误,与type={buttonType}. 错误是:

Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.

我理解这个错误。React 类型已声明“类型”属性必须是“按钮”、“重置”、“提交”或“未定义”,但我已将我的道具设置为字符串或未定义。

我的问题是,如何通过手动输入所有选项来将 React 中的选项分配给我的道具以避免重复?

编辑:这里的完整错误:

Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.
  Type 'string' is not assignable to type '"button" | "reset" | "submit" | undefined'.ts(2322)
index.d.ts(1849, 9): The expected type comes from property 'type' which is declared here on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | "style" | "title" | "className" | "color" | ... 259 more ... | "value"> & { ...; } & ButtonStyledProps, "isDisabled" | ... 267 more ... | "value"> & Partial<...>, "isDisabled" | ... 267 more ....'

@types/react 中的相关类型如下所示:

interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> {
  autoFocus?: boolean;
  disabled?: boolean;
  form?: string;
  formAction?: string;
  formEncType?: string;
  formMethod?: string;
  formNoValidate?: boolean;
  formTarget?: string;
  name?: string;
  type?: 'submit' | 'reset' | 'button';
  value?: string | string[] | number;
}

标签: javascriptreactjstypescript

解决方案


您可以使用类型查询来访问以下类型type

type ButtonType = JSX.IntrinsicElements['button']['type']

使用这种类型(或直接类型查询)作为类型buttonType应该可以解决您的问题:

export interface Props {
  buttonType?: ButtonType; // or directly JSX.IntrinsicElements['button']['type']
  handleClick?: () => void;
  href?: string;
  invertColors?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
  text: string;
  variant?: 'dark' | 'light';
}

推荐阅读