这是我的代码
import React from 'react'
import PropTypes from "prop-types";
export default function Button({ htmlType, type, disabled, action, ...props}) {
return (
<button type={htmlType} onClick={action}>
{props.children}
</button>
)
}
Button.propTypes = {
htmlType: PropTypes.string.isRequired,
action: PropTypes.func,
disabled: PropTypes.bool
};
我通过这段代码调用 Button 组件
<Button disabled={true}>button title</Button>
我想在禁用 props 为 true 时向按钮添加禁用的 html 属性,该怎么做?
最佳答案
您可以像这样排列单行 if-else 语句:
<button disabled={propsDisabled}>button title</button>
这里,propsDisabled
是可以通过props
传递的变量,它是一个boolean
变量,可以是true或错误的。为了避免混淆,我没有使用 disabled
本身,但您可以将变量名称用作 disabled
。
当 propsDisabled
为 true
时,按钮将被禁用,当 propsDisabled
为 false
时,按钮将被禁用不能被禁用。
关于html - 如何在 react 中向按钮添加禁用属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75371454/