我不确定为什么,但如果在声明中声明它们,则似乎无法调用letor const变量if/else。
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。
classes is not defined
但是,如果我改变const对var定义类,但我得到一条警告classes used outside of binding context和all var declarations must be at the top of the function scope
var
classes used outside of binding context
all var declarations must be at the top of the function scope
我该如何解决?
您应该使用三元分配:
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`
正如其他评论/答案中所指定的,let并且const它们是受限制的范围,因此这就是它们在您的示例中不起作用的原因。
对于DRYer代码,您还可以在字符串文字内部嵌套三进制:
const classes = `${withBorder ? styles.dimensions: ''} ${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`