如何在 React 的 JSX 中渲染一个布尔值

在 React 中使用 String() 函数在 JSX 中呈现布尔值,例如 <h2>{字符串(bool1)}</h2>。 默认情况下,布尔值不会在 React 中呈现任何内容,因此我们必须将值转换为字符串才能呈现它。

export default function App() {
  const bool1 = true;

  const bool2 = false;

  return (
    <div>
      <h2>bool1: {String(bool1)}</h2>

      <hr />

      <h2>bool2: {String(bool2)}</h2>
    </div>
  );
}

如何在 React 的 JSX 中渲染一个布尔值

我们必须将布尔值转换为字符串,以便在我们的 JSX 代码中显示它们。

忽略布尔值、null、undefined。 他们根本不渲染。

以下 JSX 表达式均不呈现任何内容。

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

或者,我们可以在布尔值上使用 toString() 方法将其转换为字符串。

export default function App() {
  const bool1 = true;

  const bool2 = false;

  return (
    <div>
      <h2>bool1: {bool1.toString()}</h2>

      <hr />

      <h2>bool2: {bool2.toString()}</h2>
    </div>
  );
}

Boolean.toString() 方法返回布尔值的字符串表示形式。

另一种常用的方法是使用模板文字将布尔值转换为字符串。

export default function App() {
  const bool1 = true;

  const bool2 = false;

  return (
    <div>
      <h2>{`bool1: ${bool1}`}</h2>

      <hr />

      <h2>{`bool2: ${bool2}`}</h2>
    </div>
  );
}

我们使用模板文字在字符串中插入一个布尔变量。

请注意 ,字符串包含在反引号 “ 中,而不是单引号中。

美元符号和花括号语法允许我们使用被评估的占位符。

默认情况下,模板文字将部分连接成一个字符串。