我不确定为什么,但似乎我不能调用 let
或 const
变量,如果我在 if/else
语句中声明它们。
if (withBorder) {
const classes = `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
} else {
const classes = `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
}
return (
<div className={classes}>
{renderedResult}
</div>
);
如果我使用这段代码,它会说 classes is not defined
。
But if I change the const
to var
classes is defined but I get a warning about classes used outside of binding context
and all var declarations must be at the top of the function scope
我该如何解决这个问题?
原文由 Johhan Santana 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是一个很好的例子,说明简单的三元赋值就足够了:
正如其他评论/答案中所指定的
let
和const
是块范围的,所以这就是为什么它们在你的例子中不起作用。对于 DRYer 代码,您只能对依赖它的部分使用三元: