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

为何两段含三元运算符的JSX代码一段生效一段失效?

JSX三元运算符失效原因解析

两段代码的核心差异在于三元运算的结果是否被实际使用:

第一段代码的问题

const container = document.getElementById("app");
const root = createRoot(container);

const title = '';
title === '' ? "Click an animal for a fun fact" : title; // 运算结果未被赋值或使用
const animalFacts = <h1>{title}</h1>; // 渲染的仍是原始空字符串title

root.render(animalFacts);

这段代码里,三元运算仅单独执行了一次,它返回的提示文本没有被赋值给任何变量(也没直接用于渲染)。title始终是初始的空字符串,最终<h1>自然没有内容。

第二段代码的正确逻辑

const container = document.getElementById("app");
const root = createRoot(container);

const title = '';

const animalFacts = <h1>{title === '' ? "Click an animal for a fun fact" : title}</h1>; // 直接将运算结果作为JSX内容

root.render(animalFacts);

这段代码把三元运算写在JSX的{}表达式中,运算结果会直接作为<h1>的文本内容。当title为空时,三元运算返回预期的提示文本,因此能正常渲染。

如果要修复第一段代码,只需将运算结果赋值后再使用:

const title = '';
const displayTitle = title === '' ? "Click an animal for a fun fact" : title;
const animalFacts = <h1>{displayTitle}</h1>;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:22:06