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

React Native语音转文本应用实现文本高亮功能报错求助

问题分析与修复

核心问题

你看到的[object Object]是因为把字符串和React元素数组做了字符串拼接——highlight()返回的是一组<Text>组件(本质是React元素对象),当你用+把它和字符串拼在一起时,JS会把对象强制转成[object Object]字符串。

另外你的setHighlight函数还有几个逻辑错误:

  • 索引计算错误:firstIdx = string.slice(0, array[2*i-1])多减了1,应该直接用array[2*i]作为分割点
  • 循环执行一次就return:for循环里第一次迭代就返回结果,没法处理多个高亮片段
  • 结束索引处理错误:lastIdx应该从array[2*i+1]开始截取,不是array[2*i+2]

修复方案

我们需要把setHighlight改成返回React元素数组,而非拼接字符串。具体步骤:

  1. 初始化数组存放最终文本片段(普通字符串或高亮组件)
  2. 遍历所有高亮区间,按顺序拼接非高亮文本和高亮文本
  3. 处理最后一段未高亮的文本

修复后的完整代码

import { Text, View, StyleSheet } from "react-native";
import { Component } from "react"; // 补上缺失的Component导入

const NO_WIDTH_SPACE = '​';
const highlight = string =>
  string.split(' ').map((word, i) => (
    <Text key={`highlight-word-${i}`}>
      <Text style={styles.highlighted}>{word} </Text>
      {NO_WIDTH_SPACE}
    </Text>
  ));

export default class TextBox extends Component {
  
  setHighlight = (string, highlightRanges) => {
    const result = [];
    let lastEnd = 0;

    // 遍历所有高亮区间(每两个元素为一组:起始、结束索引)
    for (let i = 0; i < highlightRanges.length; i += 2) {
      const start = highlightRanges[i];
      const end = highlightRanges[i + 1];

      // 添加高亮区间之前的普通文本
      if (start > lastEnd) {
        result.push(string.slice(lastEnd, start));
      }

      // 添加高亮的文本片段
      const highlightedSegment = string.slice(start, end);
      result.push(...highlight(highlightedSegment));

      lastEnd = end;
    }

    // 添加最后一段普通文本
    if (lastEnd < string.length) {
      result.push(string.slice(lastEnd));
    }

    return result;
  }

  render = () => {
    return(
      <View style={styles.textBox}>
        {this.props.partialResults.map((result, index) => {
          const highlightedText = this.setHighlight(result, [3, 4]); // 示例:高亮索引3到4的字符
          return (
            <Text style={styles.resultText} key={`partial-result-${index}`}>
              {highlightedText}
            </Text>
          )
        })}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  textBox: {
    marginTop: 10,
    width: 330,
    height: 400,
    backgroundColor: "white",
    borderWidth: 2,
    padding: 10,
    borderColor: "dodgerblue"
  },
  resultText: {
    fontSize: 18
  },
  highlighted: {
    padding: 2,
    backgroundColor: 'red',
  },
})

关键修复点说明

  • 用数组result收集文本片段,避免字符串拼接React元素
  • 遍历高亮区间时按顺序添加普通文本、高亮组件,最后处理剩余文本
  • 修正了索引计算错误,确保文本分割准确
  • 给highlight里的key加前缀,避免全局key冲突
  • 补上了原代码缺失的Component导入(否则会报错)

内容的提问来源于stack exchange,提问作者Woo Young Choi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:55:26