基于状态中的布尔值反应渲染:三元不工作

React rendering based on boolean in state: ternary not working

React Dev Tools 显示状态已成功更改,但未呈现正确的组件。

这是切换状态的按钮内的三元组:

return (
  <div>
    <div>{questionBlocks}</div>
    <button className="advanced-options" onClick={this.toggleAdvanced}>
      {this.state.advancedText}
      <span>
        {this.showAdvanced ? <ExpandLessIcon /> : <ExpandMoreIcon />}
      </span>
    </button>
  </div>
);

这是 toggleAdvanced 函数(它运行良好,因为我在切换 showAdvanced 时成功显示了新元素:

toggleAdvanced = (e) => {
    e.preventDefault();
    if (this.state.showAdvanced === true) {
      this.setState((prevState) => ({
        showAdvanced: !prevState.showAdvanced,
      }));
    } else {
     this.setState((prevState) => ({
       showAdvanced: !prevState.showAdvanced,
      }));
    }
};

查看了 these solutions,但没有成功。

问题大概就在这里

  <span>
        {this.showAdvanced ? <ExpandLessIcon /> : <ExpandMoreIcon />}
      </span>

您正在使用 this.showAdvanced 但它应该是 this.state.showAdvanced

你在三元中缺少 state。应该是this.state.showAdvanced,不是this.showAdvanced.