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

如何将字符串作为JSX元素的动态属性

解决JSX中添加CMS字符串属性的问题

你遇到的问题是直接对字符串使用扩展运算符...导致的——JSX会把字符串当作可迭代的字符序列,将每个字符拆解成数字键的属性,完全不符合预期。

解决思路:将字符串属性解析为对象

需要先把CMS返回的属性字符串转换成键值对对象,再用扩展运算符展开这个对象。

步骤1:编写属性解析函数

这个函数会把类似target="_blank" rel="follow"的字符串转换成React可识别的属性对象,同时建议加入属性白名单过滤危险内容:

// 允许的安全属性白名单
const ALLOWED_ATTRS = ['target', 'rel', 'title', 'aria-label'];

function parseCmsAttributes(attrStr) {
  const attrs = {};
  // 匹配属性名和带引号的值
  const attrRegex = /(\w+)\s*=\s*["']([^"']*)["']/g;
  let matchResult;

  // 先转义字符串里的"为实际引号
  const decodedStr = attrStr.replace(/"/g, '"');

  while ((matchResult = attrRegex.exec(decodedStr)) !== null) {
    const [_, attrName, attrValue] = matchResult;
    // 只保留白名单内的属性
    if (ALLOWED_ATTRS.includes(attrName)) {
      attrs[attrName] = attrValue;
    }
  }
  return attrs;
}

步骤2:在JSX中使用解析后的对象

const otherAttributes = 'target="_blank" rel="follow"';
const parsedAttrs = parseCmsAttributes(otherAttributes);

// 注意:React中用className替代class
<a href={href || ''} className="inline-block px-4 py-2 rounded-full" {...parsedAttrs}>
  {text}
</a>

为什么原写法失效?

JSX的扩展运算符...仅对对象生效,会将对象的键值对映射为元素属性。如果作用于字符串,它会把字符串拆分为字符数组,每个字符对应一个数字索引的属性(比如0="t"、1="a"),这就是你看到奇怪输出的原因。

内容的提问来源于stack exchange,提问作者M. Inam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:01:00