为何两段含三元运算符的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
相关产品推荐
相关产品推荐

