使用组件时,定义为 defaultProps 的必需 Prop 显示为缺失。

// Button.ts
interface ButtonProps {
  size: 'small' | 'medium' | 'large';
  inverted: boolean;
  raised: boolean;
}

const Button = styled('button')<ButtonProps>`...`

Button.defaultProps = {
  size: 'medium',
  inverted: false,
  raised: false,
}

export default Button
// Hello.tsx
import Button from './Button'

const Hello = () => <Button>Hello</Button>

按钮以红色突出显示并显示以下错误消息:
Type '{}' is missing the following properties from type
'Pick<Pick<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement>, "form" | "style" | "title" | "key" | "autoFocus" |
"disabled" | "formAction" | ... 255 more ... | "onTransitionEndCapture"> &
{ ...; } & ButtonProps, "form" | ... 329 more ... | "raised"> &
Partial<...>, "form" | ... 329 ...': size, inverted, and 1 more.

版本:
"@types/styled-components": "^4.1.9",
"@types/react": "^16.8.5",
"@types/react-dom": "^16.8.2",

"typescript": "^3.3.3333",
"styled-components": "^4.1.3"
"react": "^16.8.3",
"react-dom": "^16.8.3",

最佳答案

问题是分配 defaultProps 不会改变它的类型,它将保持 Partial<StyledComponentProps<"button", any, ButtonProps, never>> 的默认值。您可以明确输入 const 但输入大量类型从来都不是一件有趣的事情。一个更简单的方法是使用另一个 HOC(一切都可以用另一个 HOC 😃 解决),它改变 defaultProps 的类型以包含您在组件上实际设置的默认 Prop :

// Button.ts
interface ButtonProps {
    size: 'small' | 'medium' | 'large';
    inverted: boolean;
    raised: boolean;
}

function withDefault<T extends { defaultProps?: Partial<TDefaults> }, TDefaults>(o: T, defaultProps: TDefaults): T & { defaultProps: TDefaults } {
    o.defaultProps = defaultProps;
    return o as any;
}

const Button = withDefault(styled('button') <ButtonProps>`...`, {
    size: 'medium',
    inverted: false,
    raised: false,
})

export default Button

const Hello = () => <Button>Hello</Button> // OK now

关于reactjs - 样式化组件,定义为 defaultProps 的必需 Prop 显示为缺失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54897053/

10-13 04:51