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

React JS实现多文本多色高亮的方法求助

实现React多文本分色高亮的解决方案

核心思路

把原有的单一关键词数组改成关键词-颜色映射的对象数组,在文本匹配过程中根据每个关键词找到对应的颜色,通过内联样式或CSS类实现不同颜色的高亮效果。

修改后的完整代码

import React from "react";

function App() {
  // 定义关键词与对应高亮颜色的配置数组
  const highlightConfig = [
    { text: "Aloe Vera", color: "#ff4444" }, // 红色高亮
    { text: "and", color: "#00C851" }, // 绿色高亮
    { text: "study", color: "#ffbb33" } // 黄色高亮
  ];

  const highlightText = (text, config) => {
    // 提取所有关键词,生成匹配正则(忽略大小写)
    const keywords = config.map(item => item.text);
    const matchRegex = RegExp(keywords.join("|"), "ig");
    
    // 将原文本分割为普通文本和匹配项的交替片段
    const parts = text.split(matchRegex);
    // 获取所有匹配结果(含大小写变体)
    const matches = [...text.matchAll(matchRegex)];

    return parts.map((nonHighlightedText, index) => {
      const fragment = [];
      // 添加普通文本片段
      fragment.push(nonHighlightedText);

      // 若不是最后一段,添加对应高亮文本
      if (index < matches.length) {
        const matchedText = matches[index][0];
        // 忽略大小写匹配,找到对应颜色配置
        const targetConfig = config.find(item => 
          matchedText.toLowerCase() === item.text.toLowerCase()
        );
        fragment.push(
          <span 
            key={`highlight-${index}`}
            style={{ 
              backgroundColor: targetConfig.color,
              color: "#fff",
              padding: "0 2px",
              borderRadius: "2px"
            }}
          >
            {matchedText}
          </span>
        );
      }

      return <React.Fragment key={index}>{fragment}</React.Fragment>;
    });
  };

  return (
    <h4 style={{ lineHeight: 1.6 }}>
      {highlightText(
        "The aim of this study was to someting  in vitro the potential of Aloe Vera juice as a skin permeation enhancer; worong text is added here to which Aloe Vera itself permeates the skin. Saturated solutions of caffeine, colchicine, mefenamic acid, oxybutynin, and quinine were prepared at 32 degrees C in Aloe Vera juice and water (control) and used to dose porcine ear skin",
        highlightConfig
      )}
    </h4>
  );
}

export default App;

关键改动说明

  • 参数结构优化:将原textToMatch字符串数组替换为highlightConfig对象数组,每个元素明确绑定关键词和对应颜色。
  • 颜色映射逻辑:通过find方法忽略大小写匹配关键词,确保大小写变体的文本也能对应到正确颜色。
  • 自定义高亮样式:用<span>替代原生<mark>标签,通过内联样式灵活控制高亮的背景色、文字颜色、边距等细节,避免原生mark的默认样式限制。
  • DOM结构优化:使用React.Fragment包裹片段,避免生成多余的DOM节点,保持HTML结构整洁。

扩展建议

如果需要批量复用高亮样式,可以将样式抽离为CSS类,通过className替代style属性,方便统一管理:

.highlight-red { background-color: #ff4444; color: white; padding: 0 2px; border-radius: 2px; }
.highlight-green { background-color: #00C851; color: white; padding: 0 2px; border-radius: 2px; }
.highlight-yellow { background-color: #ffbb33; color: white; padding: 0 2px; border-radius: 2px; }

随后在代码中将style属性替换为className即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:00:50