如何在 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>
);
}
我们必须将布尔值转换为字符串,以便在我们的 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>
);
}
我们使用模板文字在字符串中插入一个布尔变量。
请注意
,字符串包含在反引号 “ 中,而不是单引号中。
美元符号和花括号语法允许我们使用被评估的占位符。
默认情况下,模板文字将部分连接成一个字符串。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。