有条件地禁用按钮

Conditional disabling of button

我想在ID达到一定数字后自动禁用按钮,比如7。代码编译但无法执行,即根据条件禁用按钮。使用 React 和 Tailwind。

    <div className="mt-8 mb-16">
      <button
        id="BTS"
        onClick={handlePurchase}
        type="button"
        disabled={this.id >= 7 }
        className="inline-flex items-center ... "
      >
        Mint me a Marköbot!
      </button>
    </div>

该应用程序的源代码位于(第 103 行)

非常感谢!

上以替代方法发布了问题

根据您的代码,this.id 是指按钮 ID 吗? 为什么不使用附加状态进行有条件禁用?

我看过你的代码,你使用函数组件,我假设 this.id 是按钮 id

您可以创建新状态并将该状态用作条件,例如

    const [buttonId, setButtonId] = React.useState(null)

    return(
        <button
          id="BTS"
          onClick={handlePurchase}
          type="button"
          disabled={buttonId >= 7 }
          className="inline-flex items-center ... "
        >
          Mint me a Marköbot!
        </button>
    )

设法解决了这个问题。发现缺少 handleClick 部分,这是渲染 'this' 内联所必需的。感谢所有提出建议的人。如果您有更简单的解决方案,请分享。

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.id = 0;
    this.handleClick = this.handleClick.bind(this);
  }

handleClick() {
  this.setState(prevState => ({
    isToggleOn: !prevState.isToggleOn
  }));
}

render() {
  return (
    <button onClick={this.handleClick}
      disabled={this.id <= 9 ? true : false}>
        {this.id <= 9 ? 'X' : 'Y'}
    </button>
  );
}
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);