You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;

关键修改点

  1. 使用模板字符串插值语法:用${变量/表达式}替代加号拼接,这是JS模板字符串的标准用法
  2. 移除多余大括号:原来的{align}和{align == 'right' ? ...}里的大括号完全多余,直接写变量和表达式即可
  3. 规范条件判断:把==换成更严谨的===(推荐在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:45:14