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

React组件Props类型推断:移除any并推导额外Props

React动态组件Props的类型安全实现

要移除[key: string]: any并实现额外Props的自动类型推断,核心是利用TypeScript泛型结合React内置的ComponentProps工具类型,让TypeScript根据传入的component类型自动推导对应的Props约束。

修改后的Button组件实现

import { PropsWithChildren, ElementType, ComponentProps } from 'react';

// 定义泛型Props类型:固定component属性 + 对应元素的Props(排除children,由PropsWithChildren统一处理)
type ButtonProps<C extends ElementType> = PropsWithChildren<{
  component: C;
} & Omit<ComponentProps<C>, 'children'>>;

// 泛型组件,默认渲染button标签
export const Button = <C extends ElementType = 'button'>(
  props: ButtonProps<C>
) => {
  const { component: Component = 'button', children, ...restProps } = props;
  return <Component {...restProps}>{children}</Component>;
};

关键逻辑说明

  1. 泛型约束:用C extends ElementType限制component的类型,可以是原生HTML标签(如'button'、'a')或自定义组件。
  2. 自动推导Props:通过ComponentProps<C>获取传入组件的完整Props类型,再用Omit排除children(避免与PropsWithChildren的children属性冲突)。
  3. 默认值处理:给泛型C设置默认值'button',用户不传入component时,默认使用button标签并自动获得button的Props类型约束。
  4. 类型安全验证:当传入的Props与component类型不匹配时,TypeScript会直接报错。比如给component='button'传入href属性,会提示button标签不存在该属性。

用法示例

// 合法:a标签支持href属性
<Button component='a' href='/home' target='_blank'>
  跳转到首页
</Button>

// 合法:button标签支持disabled属性
<Button component='button' disabled>
  不可点击按钮
</Button>

// 报错:button标签没有href属性
<Button component='button' href='x'>
  Push Me
</Button>

内容的提问来源于stack exchange,提问作者CzechCoder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:33:40