You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS类组件中如何基于多条件判断返回对应按钮

React 类组件按条件渲染按钮实现方案

下面提供两种常用的实现方式,可根据业务逻辑复杂度选择:

写法1:JSX内嵌套三元运算符(适合逻辑简单的场景)

直接在render方法的返回值中嵌入判断即可:

render() {
  // 注意此处变量取值来源请根据实际情况调整,若来自props请换成this.props
  const { credentials, username, paused } = this.state;
  return (
    <div>
      {/* 此处省略你组件其他渲染内容 */}
      {credentials.username === username ? (
        paused ? (
          <MyButton
            tip="Un Pause Job"
            onClick={this.handleUnPause}
          >
            Unpause
          </MyButton>
        ) : (
          <MyButton
            tip="Pause Job"
            onClick={this.handlePause}
          >
            Pause
          </MyButton>
        )
      ) : null}
    </div>
  )
}

写法2:提前计算渲染内容(逻辑复杂更推荐,可读性和可维护性更高)

把条件判断逻辑抽离到return语句之前,后续要新增判断条件时更方便修改:

render() {
  // 注意此处变量取值来源请根据实际情况调整,若来自props请换成this.props
  const { credentials, username, paused } = this.state;
  let actionButton = null;

  if (credentials.username === username) {
    actionButton = paused ? (
      <MyButton
        tip="Un Pause Job"
        onClick={this.handleUnPause}
      >
        Unpause
      </MyButton>
    ) : (
      <MyButton
        tip="Pause Job"
        onClick={this.handlePause}
      >
        Pause
      </MyButton>
    )
  }

  return (
    <div>
      {/* 此处省略你组件其他渲染内容 */}
      {actionButton}
    </div>
  )
}

提示:如果你的handlePause和handleUnPause方法没有提前绑定this,需要在构造函数中绑定,或者写成箭头函数方法,避免点击时this指向错误。

内容的提问来源于stack exchange,提问作者benpalmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:54:03