JavaScript中如何正确使用单行if语句在JSX中绑定className?
错误原因
JSX 语法要求 {} 内部只能传入 JavaScript 表达式,你写的 if (typeof title === 'string') classes.title 属于条件语句,不是表达式,所以解析器会抛出 Parsing error: Expression expected 错误。
可行的单行写法
- 逻辑与短路写法
条件成立时返回对应类名,不成立时返回undefined,React 会自动忽略无效的 className 值,是最简洁的实现:
<Typography className={ typeof title === 'string' && classes.title } >{ title }</Typography>
- 三元运算符写法
如果需要指定条件不成立时的类名,用三元运算符逻辑更清晰:
<Typography className={ typeof title === 'string' ? classes.title : classes.alternativeTitle } >{ title }</Typography>
不需要备用类名时直接返回 undefined 即可:
<Typography className={ typeof title === 'string' ? classes.title : undefined } >{ title }</Typography>
- 多类名拼接场景(Material-UI 项目推荐)
如果需要同时拼接多个固定/动态类名,可以使用 MUI 内置的clsx工具,无需额外安装依赖:
import clsx from 'clsx'; <Typography className={ clsx(classes.baseStyle, typeof title === 'string' && classes.title) } >{ title }</Typography>
内容的提问来源于stack exchange,提问作者Rob Bauer
相关产品推荐
相关产品推荐

