【问题标题】:How to apply a single line if statement in Javascript?如何在 Javascript 中应用单行 if 语句?
【发布时间】:2021-11-22 03:54:51
【问题描述】:

我想使用像here 中描述的单行 if 语句返回一个类。在我的方法中,我使用的是 Material-UI 并想设置一个类。

所以我想用这个方法if(condition) expression

    <Typography className={ if (typeof title === 'string') classes.title } >{ title }</Typography>

我收到以下错误:解析错误:预期表达式

我在这里做错了什么?

【问题讨论】:

    标签: javascript if-statement material-ui shorthand


    【解决方案1】:

    你可以这样写: typeof 标题 === '字符串' ? classes.title : ''

    没试过,应该可以的。

    【讨论】:

    • 感谢您的回复。我知道这行得通。但我真的很想这样写:if(condition) expression
    • 为什么?结果是一样的
    • 我知道,但我认为它更具可读性,我不必定义 else 选项
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2015-05-16
    相关资源
    最近更新 更多