我可以在条件渲染中使用多个状态值吗 - ReactJs

Can i use multiple state value inside conditional rendering - ReactJs

我想知道如何在条件渲染中使用两个基于状态的布尔值。例如,如果其中一个条件为真,我想渲染某个 <div> 元素,否则不渲染它 示例:

{
 this.state.visible && this.state.checked &&
 <div>
  ...
 </div>
}

为了显示我的错误消息,我使用了这个示例,但初始化时我有对象的 .length,因此使用起来很容易,例如:

 {
  this.state.ErrorMessage.length > 0 &&
 <p>Error 404</p>
 }

有人可以提醒我一下吗?我有点困惑。

您可以按照括号中的方式进行操作,以检查两者是否正确:

{
    (this.state.visible && this.state.checked) &&  <div>...</div> 
}

如果您希望其中之一为真:

{
    (this.state.visible || this.state.checked) &&  <div>...</div> 
}

将其作为一个单独的函数使用,returns 组件基于条件。

示例:

renderConditionalComponent() {
  const { visible, checked } = this.state;

  if (visible || checked) {
    return <Component1 />;
  }

  // There could be other condition checks with different components.
  // ...

  return null;
}

render() {
  // ...
  return (
    <div>
      {this.renderConditionalComponent()}
      {/* other components, etc */}
      <OtherComponent />
    </div>
  );
}