javascript - React FunctionComponent 上 defaultProps 的 Typescript 错误

标签 javascript reactjs typescript

我有以下 React 功能组件:

import React, { memo } from 'react';

interface Props {
  buttonType?: JSX.IntrinsicElements['button']['type'];
  text: string;
};

const defaultProps = {
  buttonType: 'button',
};

const Button: React.FunctionComponent<Props> = ({
  buttonType,
  text,
}) => (
  <button type={buttonType}>
    {text}
  </button>
);

Button.defaultProps = defaultProps;

export default memo(Button);

这会引发 Typescript 错误:

Type '{ buttonType: string; }' is not assignable to type 'Partial<Props>'.

这就是我通常编写无状态组件的方式,这里的错误是因为我将 defaultProps 分配给组件。如果我将 defaultProps 声明写为:

Button.defaultProps = {
  buttonType: 'button',
};

为什么在从 const 分配 defaultProps 时会出现错误,但如果我全部内联分配则不会出现错误?这不是一回事吗?

最佳答案

您必须在 defaultProps 对象上指定 buttonType 的类型。当您使用 Button.defaultProps 时,这会自动推断为 JSX.IntrinsicElements['button']['type'],但是当您创建一个新对象时,它会看到它作为一个字符串

const defaultProps: Partial<Props> = {
  buttonType: 'button',
}

应该可以

关于javascript - React FunctionComponent 上 defaultProps 的 Typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56476299/

相关文章:

javascript - JS正则表达式匹配字符之间最大1个空格的字符串

reactjs - 每次有人使用 firebase 和 Reactjs 访问页面时计算浏览次数

javascript - 防止 React-Select 永远为空

带有一般错误的 typescript 缩小类型

node.js - tsc 错误 TS1110 node.d.ts Node.js v6.x

javascript - JS/TS 如何迭代对象数组并更改值

javascript - 使用 angular-bootstrap 时 $injector 错误($modalInstanceProvider <- $modalInstance)

javascript - 在数组中,我怎样才能按照我希望打印的方式打印值而不是最后一个值?

javascript - React : In a map loop, 如何在打印四列后打破表格行?

javascript - (角色扮演游戏?)HTML5 和 Javascript 中的对话系统 - 这可能吗?