【发布时间】:2019-06-06 11:05:51
【问题描述】:
我有以下 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 时会出现错误,但如果我全部内联则不会?不是一样的吗?
【问题讨论】:
标签: javascript reactjs typescript