我有以下 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/