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

如何在JSX中输出句子并为匹配指定单词的文本着色?

解决方法

你只需要在map遍历的时候增加判断逻辑,匹配到目标单词时用带样式的标签包裹即可,同时要处理单词间的空格避免文字连在一起:

export default function App() {
  const defaultText = "Your partner for software innovations";
  const colorText = "software";

  const result = defaultText.split(" ").map((txt, index, arr) => {
    // 判断当前单词是否需要着色
    if (txt === colorText) {
      return (
        <span key={index} style={{ color: "red" }}>
          {txt}
          {/* 最后一个单词不加空格 */}
          {index !== arr.length - 1 ? " " : ""}
        </span>
      );
    }
    // 普通单词直接返回,加空格分隔(最后一个除外)
    return `${txt}${index !== arr.length - 1 ? " " : ""}`;
  });

  return <div className="App">{result}</div>;
}

补充说明

  • 如果项目用CSS类管理样式更规范,可以定义一个CSS类替代行内样式:
    .highlight-red {
      color: red;
    }
    
    然后把<span>的style换成className="highlight-red"即可。
  • 用index作为key在这里是可行的,因为单词列表是静态的(来自后端固定文本),不会出现元素重新排序的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:50:22