You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:40:29