【问题标题】:How to add disabled attribute to button in react?如何在反应中向按钮添加禁用属性?
【发布时间】:2023-02-07 17:46:47
【问题描述】:

这是我的代码

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>

我想在 disabled of props 为真时向按钮添加 disabled html 属性,该怎么做?

【问题讨论】:

  • 您实际上需要将禁用属性添加到真实按钮:return &lt;button type={htmlType} onClick={action} disabled={disabled}&gt;{props.children}&lt;/button&gt;
  • 只需将禁用传递给按钮。像这样:<button disabled={Boolean(disabled)} ...

标签: html reactjs react-props


【解决方案1】:

您可以将单行 if-else 语句排成一行,如下所示:

<Button disabled={propsDisables?true:false}>button title</Button>

在这里,propsDisabled 是您可以通过 props 传递的变量,它是一个 boolean 变量,可以为真或为假。为了避免混淆,我没有使用 disabled 本身,但您可以将变量名称用作 disabled

当它是true时,按钮将被禁用,当它为假时,按钮将不会被禁用,即disabled:false

【讨论】:

  • AFAIK disabled={propsDisabled} 也可以正常工作。
  • @Dimitar 是的,那也行,我会把它包括在编辑中,谢谢 :)
猜你喜欢
  • 1970-01-01
  • 2017-12-03
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2022-12-22
  • 2023-04-03
相关资源
最近更新 更多