React/Next.js组件中如何在className中使用三元运算符?
React/Next.js Section组件className语法错误修复
你当前的代码报错是因为模板字符串拼接时的语法错误:
- 错误地在变量和表达式外层加了大括号
{},导致JS解析失败 - 混合使用模板字符串与加号拼接,写法不符合JS语法规范
修复后的代码
function Section({ idVal, text, title, align }) { return ( <div id={idVal} className={`mt-12 w-full h-fit text-${align} grid place-items-${align === 'right' ? 'end' : 'start'}`} > <div className="text-4xl text-white text-end mt-20 mr-[15vw] border-b-[1px] border-b-slate-500 w-96 pl-5 rotate-2"> <h2 className="mr-[4vw] -rotate-2">{title}</h2> </div> <p className="text-white w-[38vw] mr-[28vw] mt-8 whitespace-pre-line"> {text} </p> </div> ); } export default Section;
关键修改点
- 使用模板字符串插值语法:用
${变量/表达式}替代加号拼接,这是JS模板字符串的标准用法 - 移除多余大括号:原来的
{align}和{align == 'right' ? ...}里的大括号完全多余,直接写变量和表达式即可 - 规范条件判断:把
==换成更严谨的===(推荐在React/JS开发中使用全等判断)
如果是TypeScript项目,建议给props添加类型定义,避免类型错误:
interface SectionProps { idVal: string; text: string; title: string; align: 'left' | 'right'; // 限制align的可选值范围 } function Section({ idVal, text, title, align }: SectionProps) { // ... 组件内容 }
内容的提问来源于stack exchange,提问作者Nolan Knight
相关产品推荐
相关产品推荐

