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

如何将传入React组件的对象文本部分设置为粗体?

解决React中描述文本部分加粗的问题

方案1:将描述内容定义为JSX数组

React支持直接渲染JSX数组,把需要加粗的文本用<b>或<strong>标签包裹,其余部分作为字符串组合成数组即可,同时给JSX元素加key避免React警告。

修改agencyProps:

const agencyProps = {
  title: "Managed agency selection",
  paragraph: "Strengten your onboarding process",
  videoImage: {
    src: "/img/video.png",
    alt: "background",
    width: 330,
    height: 520,
  },
  selections: {
    cardOne: {
      title: "Brief",
      description: [
        "Complete brief or ",
        <b key="bold-section">THIS</b>,
        " simple guidance on what to include, we've got you covered"
      ],
      width: "430px",
    },
    cardTwo: {
      title: "Search",
      description:
        "In-depth agency search covering, criteria matching, door knocking and due-dilligence vetting.",
      width: "460px",
    },
    cardThree: {
      title: "Pitch",
      description:
        "Comprehensive pitch management, including comms, diary management and pitch hosting.",
      width: "490px",
    },
  },
};

组件中直接渲染:

<StyledSelectDescription>
  {selections.cardOne.description}
</StyledSelectDescription>

方案2:使用dangerouslySetInnerHTML(适合静态可信内容)

如果希望保持字符串格式,可在字符串中直接写HTML标签,通过dangerouslySetInnerHTML让React解析HTML。注意:仅当内容是静态、可信的时使用,避免XSS风险。

修改agencyProps:

const agencyProps = {
  // 其他属性不变
  selections: {
    cardOne: {
      title: "Brief",
      description: "Complete brief or <b>THIS</b> simple guidance on what to include, we've got you covered",
      width: "430px",
    },
    // 其他card属性不变
  },
};

组件中渲染:

<StyledSelectDescription
  dangerouslySetInnerHTML={{ __html: selections.cardOne.description }}
/>

方案3:拆分文本与加粗片段(灵活适配不同位置)

在对象中单独定义基础文本和需要加粗的内容,组件里通过字符串拆分拼接实现渲染:

修改agencyProps:

const agencyProps = {
  // 其他属性不变
  selections: {
    cardOne: {
      title: "Brief",
      baseText: "Complete brief or simple guidance on what to include, we've got you covered",
      boldContent: "THIS",
      replaceTarget: "simple", // 指定要替换为加粗文本的关键词
      width: "430px",
    },
    // 其他card属性不变
  },
};

组件中处理渲染:

<StyledSelectDescription>
  {selections.cardOne.baseText.split(selections.cardOne.replaceTarget).join(<b>{selections.cardOne.boldContent}</b>)}
</StyledSelectDescription>

为什么之前的方法无效?

  • 直接在字符串里加<b>标签:React默认会转义所有字符串内容,把标签当作普通文本渲染,不会解析成HTML元素。
  • 使用getter或单独的bold属性:如果没有在组件里将bold属性和description拼接成可识别的JSX结构,也无法触发加粗效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:20:27