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

React项目中能否在对象数组的模板字符串内插入JSX元素?

在React中向对象数组的描述字段插入JSX元素的解决方案

你尝试在React项目的portfolio.jsx数组对象的description模板字符串中插入<a>等JSX元素,但页面显示[object Object]或字符串化的元素,两种插入方式均无效。

问题原因

模板字符串会将插入的JSX对象强制转换为字符串,而JSX对象转字符串的结果就是[object Object],因此直接在模板字符串中插入JSX的方式行不通。

解决方案

方法1:将description改为字符串与JSX的混合数组

把description字段从模板字符串改成包含字符串和JSX元素的数组,React可以直接渲染数组中的混合内容。

修改portfolio.jsx:

const learnReactLink = (
  <a href="https://scrimba.com/learn/learnreact" target="_blank" rel="noopener noreferrer">
    Learn React for free
  </a>
)

export default [
  {
    title: "Tenzies Game",
    imgUrl: "images/projects/tenziesgamepreview.png",
    description: [
      "This is the final Capstone Project for ",
      learnReactLink,
      " that taught me a lot about React, everything from props, state, making API calls, useEffects, React forms, and more!"
    ],
    stack: [reactLogo, sassLogo],
    link: "https://fredtenziesgame.netlify.app/",
    codeLink: "https://github.com/fred-gutierrez/tenzies-game",
  }
]

在ProjectsItem.jsx中直接渲染description:

<div className="project-description">
  {description}
</div>

方法2:将description设为返回JSX的函数(可选)

如果需要处理更复杂的逻辑,可以把description定义为一个函数,返回拼接好的JSX内容:

修改portfolio.jsx:

export default [
  {
    title: "Tenzies Game",
    imgUrl: "images/projects/tenziesgamepreview.png",
    description: () => (
      <>
        This is the final Capstone Project for{" "}
        <a href="https://scrimba.com/learn/learnreact" target="_blank" rel="noopener noreferrer">
          Learn React for free
        </a>
        {" that taught me a lot about React, everything from props, state, making API calls, useEffects, React forms, and more!"}
      </>
    ),
    stack: [reactLogo, sassLogo],
    link: "https://fredtenziesgame.netlify.app/",
    codeLink: "https://github.com/fred-gutierrez/tenzies-game",
  }
]

在ProjectsItem.jsx中调用该函数渲染:

<div className="project-description">
  {description()}
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:10:23