React Native中如何实现文本指定单词首次出现时高亮可点击
实现方案
直接按顺序匹配高亮词的首次出现位置,拆分文本后拼接普通文本和高亮可点击组件即可,完全适配动态数量的高亮词,无需硬编码对应每一个高亮项。
完整实现代码
import React from "react" import { Text, View, Pressable } from "react-native" 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 WordBoxText = () => { const renderHighlightText = () => { let remainingText = data.text const renderElements = [] // 记录已处理的高亮词,避免重复高亮 const processedWords = new Set() // 可选:如果需要按单词在文本中的出现顺序高亮,而非highlight数组的顺序,可先做排序 // const sortedHighlight = [...data.highlight].sort((a,b) => data.text.indexOf(a) - data.text.indexOf(b)) data.highlight.forEach(word => { if (processedWords.has(word)) return const firstIndex = remainingText.indexOf(word) // 文本中不存在该单词直接跳过 if (firstIndex === -1) return // 先插入高亮词前面的普通文本 if (firstIndex > 0) { renderElements.push( <Text key={`text-${renderElements.length}`}> {remainingText.slice(0, firstIndex)} </Text> ) } // 插入可点击的高亮文本 renderElements.push( <Pressable key={`highlight-${word}`} onPress={() => { // 此处写点击高亮词的业务逻辑 console.log(`点击了高亮词:${word}`) }} > <Text style={{ color: "red" }}>{word}</Text> </Pressable> ) // 更新剩余待处理的文本,切掉已经处理过的部分 remainingText = remainingText.slice(firstIndex + word.length) processedWords.add(word) }) // 插入最后剩下的普通文本 if (remainingText.length > 0) { renderElements.push(<Text key="text-final">{remainingText}</Text>) } return renderElements } return ( <View style={{ marginTop: 100, paddingHorizontal: 16 }}> <Text>{renderHighlightText()}</Text> </View> ) } export default WordBoxText
逻辑说明
- 支持
data.highlight中任意数量的高亮词,无需修改代码适配 - 同一单词多次出现时仅首次出现位置高亮,重复的高亮词也不会重复处理
- 高亮文本包裹了
Pressable组件,可直接自定义点击事件 - 如果需要严格匹配整词(避免命中长单词的子串),把
indexOf匹配替换为正则全词匹配即可
内容的提问来源于stack exchange,提问作者SoF
相关产品推荐
相关产品推荐

