使用 if else 来声明 \`let\` 或 \`const\` 在 if/else 之后使用?

新手上路,请多包涵

我不确定为什么,但似乎我不能调用 letconst 变量,如果我在 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 许可协议

阅读 836
2 个回答

这是一个很好的例子,说明简单的三元赋值就足够了:

 const classes = withBorder ?
 `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center` :
 `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`

正如其他评论/答案中所指定的 letconst 是块范围的,所以这就是为什么它们在你的例子中不起作用。

对于 DRYer 代码,您只能对依赖它的部分使用三元:

  const classes = (withBorder ? `${styles.circularBorder} ` : "") +
 `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`

原文由 maioman 发布,翻译遵循 CC BY-SA 4.0 许可协议

letconst 是块级作用域,这意味着它们只能在它们已在 ie 中定义的块内使用。 { // if defined in here can only be used here }

在这种情况下,我将在 if/else 语句之上定义

let classes;

if (withBorder) {
  classes = `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
} else {
  classes = `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
}

原文由 finalfreq 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题