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

React中如何为自定义Button组件添加disabled属性?

解决方案

直接将组件接收的disabled props传递给原生<button>元素即可。在React中,布尔类型的属性如果值为true,会自动渲染为对应的HTML属性;如果值为false或未传递,则不会渲染该属性。

修改后的Button组件代码如下:

import React from 'react'
import PropTypes from "prop-types";

export default function Button({ htmlType, type, disabled, action, ...props}) {
  return (
    <button 
      type={htmlType} 
      onClick={action}
      disabled={disabled} {/* 绑定disabled属性 */}
    >
        {props.children}
    </button>
  )
}

Button.propTypes = {
    htmlType: PropTypes.string.isRequired,
    action: PropTypes.func,
    disabled: PropTypes.bool
};

这样当你通过<Button disabled={true}>button title</Button>调用组件时,原生button会自动带上disabled属性,按钮变为不可点击状态;如果传递disabled={false}或者不传递该props,按钮则保持可点击状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:11:08