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

React中如何将HTML原生属性作为props传递给自定义组件

你写的这种写法完全可行,不需要逐个声明所有HTML button原生属性,这种透传props的方式也是React中封装通用基础组件的常规实践。

  • 原理说明:你通过...htmlAttributesOnly剩余参数收集了除children外所有传入的props,再通过JSX展开语法{...htmlAttributesOnly}全部绑定到原生button元素上,所有原生button支持的属性(包括type、className、disabled、各类事件回调等)都会正常生效,和直接使用原生button的表现完全一致。
  • 如果使用TypeScript,还可以添加类型约束获得类型提示与合法性校验,示例代码如下:
import type { ButtonHTMLAttributes } from 'react';

// 继承原生button所有属性的类型定义
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement>;

const Button = ({ children, ...rest }: ButtonProps) => {
  return <button {...rest}>{children}</button>;
};
  • 需要拓展自定义功能时,只需要显式解构出自定义参数处理即可,不会影响原生属性透传,比如新增自定义size属性的示例:
const Button = ({ children, size = 'default', ...rest }) => {
  // 处理自定义属性逻辑
  const sizeClass = `btn-${size}`;
  // 合并透传的className和自定义类名
  const finalClassName = rest.className ? `${rest.className} ${sizeClass}` : sizeClass;

  return (
    <button 
      {...rest} 
      className={finalClassName}
    >
      {children}
    </button>
  );
};
  • 注意事项:属性绑定的优先级为后写的属性会覆盖前面的属性,如果需要设置默认属性,直接写在展开运算符前面即可;如果需要强制覆盖用户传入的属性,写在展开运算符后面即可。比如给按钮设置默认type为button:
// 用户传入type时会覆盖默认值
<button type="button" {...rest}>{children}</button>

// 强制所有按钮type为button,即使用户传入也会被覆盖
<button {...rest} type="button">{children}</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:45:04