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
相关产品推荐
相关产品推荐

