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

如何在React的JSX属性字符串中插入JavaScript变量?

你之前的代码有两处核心错误:

  1. React 中给元素属性传动态值必须用大括号{}包裹模板字符串,不能直接把反引号写在属性值的位置
  2. 如果你使用的是 Tailwind CSS,不支持bg-${变量}这种不完整类名的动态拼接,Tailwind 的 JIT 编译器需要扫描到完整的类名才会生成对应样式,动态拼接的类名会无法生效。

正确实现方案

方案1:预定义类名映射(适配Tailwind CSS,最稳妥)

提前把允许传入的颜色值和完整的Tailwind类名做映射,保证Tailwind可以扫描到所有用到的类名,样式不会丢失:

// 自定义Button组件定义
const Button = ({
  bg = 'black', // 默认背景色
  textColor = 'white', // 默认文字色
  children
}) => {
  // 背景色类名映射,可根据业务需求扩展
  const bgClass = {
    black: 'bg-black',
    red: 'bg-red-500',
    blue: 'bg-blue-500',
    green: 'bg-green-500'
  }[bg]

  // 文字色类名映射,可根据业务需求扩展
  const textClass = {
    white: 'text-white',
    black: 'text-black',
    gray: 'text-gray-700'
  }[textColor]

  return (
    <button className={`px-6 py-2 rounded-full ${bgClass} ${textClass}`}>
      {children}
    </button>
  )
}

// 组件调用示例
// 不传参数时使用默认样式
<Button>默认按钮</Button>
// 传入自定义参数覆盖样式
<Button bg="red" textColor="black">红色按钮</Button>

方案2:自定义CSS类场景(无Tailwind限制)

如果你是用自定义CSS类,不需要考虑Tailwind的类扫描规则,只要把模板字符串用大括号包裹即可:

<button className={`btn px-6 py-2 bg-${props.bgColor} rounded-full`}>shop</button>

方案3:支持任意自定义颜色

如果需要支持任意传入的颜色值,可直接配合style属性实现:

<button 
  className="px-6 py-2 rounded-full"
  style={{
    backgroundColor: props.bgColor || 'black',
    color: props.textColor || 'white'
  }}
>
  shop
</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:18:03