使用if else声明在if / else之后使用`let`或`const`? [英] Use if else to declare a `let` or `const` to use after the if/else?

查看:1137
本文介绍了使用if else声明在if / else之后使用`let`或`const`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定为什么,但似乎我不能调用 const 变量我在 if / else 语句中声明它们。

I'm not sure why but it seems that I can't call the let or const variables if I declare them in an if/else statement.

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>
);

如果我使用此代码,则表示未定义

If I use this code it says that classes is not defined.

但如果我将 const 更改为 var 定义了类,但我收到关于在绑定上下文之外使用的类的警告所有var声明必须位于函数的顶部范围

But if I change the const to var classes is defined but I get a warning about classes used outside of binding contextand all var declarations must be at the top of the function scope

我该如何解决这个问题?

How could I fix this?

推荐答案

你应该使用三元赋值:

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`

正如其他评论/答案中所指定的那样 const 被阻止范围,这就是为什么它们不起作用的原因您的示例。

As specified in other comments/answers let and const are blocked scope so that's why they don't work in your example.

对于DRYer代码,您还可以将三元嵌套在字符串文字中:

For a DRYer code you can also nest the ternary inside string literal:

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

这篇关于使用if else声明在if / else之后使用`let`或`const`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆