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

React Native 如何实现文本指定单词仅首次出现时可点击高亮

实现方案

核心思路

  • 先把需要高亮的目标词存入Set结构,方便后续快速校验和删除已处理的词
  • 用带单词边界的正则全局匹配所有目标词,避免误匹配包含目标词的长单词
  • 每次匹配到目标词时校验是否还在待处理集合中:是则替换为高亮可点击元素,同时将该词从待处理集合移除;否则直接返回原文本,不做处理
  • 特殊场景注意:如果目标词包含正则特殊字符(如.,*,+等),需要先对每个目标词做正则转义再拼接正则,避免匹配异常

原生JS实现代码

const data = {
    text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, dummy when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    highlight: ["dummy", "standard", "since"]
}

// 初始化待高亮词集合
const pendingHighlight = new Set(data.highlight);
// 构造全词匹配正则
const matchReg = new RegExp(`\\b(${data.highlight.join('|')})\\b`, 'g');

// 文本替换处理
const renderHtml = data.text.replace(matchReg, (matchedWord) => {
  if (pendingHighlight.has(matchedWord)) {
    pendingHighlight.delete(matchedWord);
    // 替换为带高亮样式和点击属性的span
    return `<span class="highlight" data-word="${matchedWord}">${matchedWord}</span>`;
  }
  return matchedWord;
});

// 高亮样式(可写入CSS文件)
// .highlight {
//   color: #f00;
//   cursor: pointer;
// }

// 点击事件用事件委托绑定,性能更好
document.querySelector('#text-container').addEventListener('click', (e) => {
  if (e.target.classList.contains('highlight')) {
    const clickWord = e.target.dataset.word;
    // 此处写自定义点击交互逻辑
    console.log('点击了高亮词:', clickWord);
  }
});

// 插入到页面容器
document.querySelector('#text-container').innerHTML = renderHtml;

框架适配

  • Vue项目:处理后的HTML字符串用v-html渲染到容器,点击事件同样用事件委托绑定在容器元素上即可
  • React项目:可以将匹配结果拆分为文本节点和React元素数组进行渲染,不需要使用dangerouslySetInnerHTML,安全性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:45:04