html - 如何在 react 中向按钮添加禁用属性?

标签 html reactjs react-props

这是我的代码

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

propsDisabledtrue 时,按钮将被禁用,当 propsDisabledfalse 时,按钮将被禁用不能被禁用。

关于html - 如何在 react 中向按钮添加禁用属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75371454/

相关文章:

html - 使所有链接颜色为灰色

reactjs - 如何在 react-router-dom v4.2.2 中获取当前路由

javascript - this.state 与 React 中的状态

reactjs - React 在父级状态更改后更新子级的 props

javascript - 如何使用 jsPDF 和 canvas 生成 PDF?

jQuery - 淡入速度不起作用

html - 如何加入专线?

javascript - this.setState() 不会重新渲染

javascript - requireNativeComponent : "RNSScreenStackHeaderConfig" was not found in the UIManager when running android app

javascript - 如何将 props 传递给作为值传递的组件