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

NextJS:如何根据多条件为Button组件添加样式

解决Next.js Button组件主题样式不生效的问题

你的代码里className的拼接逻辑存在错误——无论传入的theme是什么值,都会同时添加橙色系列和蓝色系列的其中一个类。比如当theme="primaryBlue"时,会同时应用styles.secondaryOrange和styles.primaryBlue,两个类的background-color和color属性会相互覆盖,导致样式不符合预期。

方案一:修正条件判断逻辑

只根据theme的值选择对应的单个主题类,避免样式冲突:

import styles from "./Button.module.css"

interface IButton {
  text?: string
  theme?: string
  onClick: () => void
}

export default function Button({ theme = "secondaryOrange", text, onClick }: IButton) {
  let themeClass = styles.secondaryOrange; // 设置默认主题

  if (theme === "primaryOrange") {
    themeClass = styles.primaryOrange;
  } else if (theme === "primaryBlue") {
    themeClass = styles.primaryBlue;
  } else if (theme === "secondaryBlue") {
    themeClass = styles.secondaryBlue;
  }

  return (
    <button
      className={`${styles.btn} ${themeClass}`}
      onClick={onClick}
    >
      {text}
    </button>
  )
}

方案二:用对象映射优化代码(更简洁易维护)

通过对象映射关联主题与类名,后续新增主题时只需扩展映射对象,代码可读性更高:

import styles from "./Button.module.css"

interface IButton {
  text?: string
  theme?: "primaryOrange" | "secondaryOrange" | "primaryBlue" | "secondaryBlue"
  onClick: () => void
}

// 主题与对应类名的映射表
const themeClassMap = {
  primaryOrange: styles.primaryOrange,
  secondaryOrange: styles.secondaryOrange,
  primaryBlue: styles.primaryBlue,
  secondaryBlue: styles.secondaryBlue,
};

export default function Button({ theme = "secondaryOrange", text, onClick }: IButton) {
  // 若传入无效主题, fallback 到默认主题
  const themeClass = themeClassMap[theme] || themeClassMap.secondaryOrange;

  return (
    <button
      className={`${styles.btn} ${themeClass}`}
      onClick={onClick}
    >
      {text}
    </button>
  )
}

额外注意事项

  • 给theme设置默认值,避免未传入主题时出现样式异常;
  • 给theme添加类型约束(如方案二),防止传入无效的主题字符串;
  • 原代码中接口定义了onClick但组件未绑定,需补充绑定避免TS报错。

内容的提问来源于stack exchange,提问作者ST80

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:25:18