如何在TypeScript中重写@emotion/styled的Input默认size属性
解决Input组件默认size属性的问题
你的需求是限定Input组件的size可选值为"md" | "lg",同时解决size为undefined的问题,以下是两种可行方案:
方案一:在样式回调中直接设置默认值
在解构props时给size指定默认值,确保未传入size时使用预设值:
interface InputProps { size?: keyof typeof theme.padding.rect; // 可选值为"md" | "lg" } const Input = styled.input<InputProps>(({theme, size = "md"}) => ({ backgroundColor: theme.colors.dark.background.primary, border: theme.colors.dark.border, borderRadius: theme.borderRadius, padding: theme.padding.rect[size], // size不再是undefined }))
方案二:通过defaultProps统一设置默认值
利用styled-components支持的defaultProps特性,为组件配置默认属性:
interface InputProps { size?: keyof typeof theme.padding.rect; // 可选值为"md" | "lg" } const Input = styled.input<InputProps>(({theme, size}) => ({ backgroundColor: theme.colors.dark.background.primary, border: theme.colors.dark.border, borderRadius: theme.borderRadius, padding: theme.padding.rect[size!], // 用非空断言确保类型安全 })) // 绑定默认属性 Input.defaultProps = { size: "md" }
注意事项
- 方案一写法更简洁,推荐优先使用;
- 如果业务要求必须传入size,可将接口中的
size?改为size(移除可选标记),强制外部传值。
内容的提问来源于stack exchange,提问作者Charisman Apriandi
相关产品推荐
相关产品推荐

