将本机拆分字符串分解为多个文本标签 [英] React Native split string into multiple text tags

查看:82
本文介绍了将本机拆分字符串分解为多个文本标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,即大量文本(在我的情况下为ToS)无法正确显示在屏幕上(当字符串使文本字段大于8000高度时发生).我已经读过该问题的解决方案是将ToS拆分为多个文本标签.

I have an issue where amounts of text (in my case a ToS) is not rendering properly onto the screen (this occurs when the string makes the text field larger than a height of 8000). I've read the solution to the problem is to split the ToS into multiple text tags.

我该如何在每一行中拆分字符串并以编程方式为其生成文本标签?

How could I go about splitting the string at every new line and programatically generating a text tag for it?

例如:

"paragraph1...

paragraph2...."

进入:

<Text>paragraph1...</Text>
<Text>paragraph1...</Text>

推荐答案

这未经测试,但是我在自己构建的应用中做了类似的事情.

This is untested, but I did something similar in an app I built.

原理是循环遍历文本字符串并将其拆分为任意长度的块,将每个块包装在其自己的<Text>元素中,然后将其附加到数组中.

The principle is that you loop through your text string and split it into chunks of whatever desired length, wrapping each chunk in it's own <Text> element and appending it to an array.

编辑:或者,您可以修改此功能以将字符串拆分为换行符,而不是指定的长度.

Edit: Alternatively, you could modify this function to split the string on newline character instead of a specific length.

import { Text } from 'react-native';

export function split(string, length = 1000) {
  // Split text into individual words and count length
  const words = string.split(' ');
  const count = words.length;

  // Prepare elements and position tracker
  const elements = [];
  let position = 0;

  // Loop through words whilst position is less than count
  while (position < count) {
    // Prepare text for specified length and increment position
    const text = words.slice(position, length).join(' ');
    position += length;

    // Append text element
    elements.push((
      <Text>{text}</Text>
    ));
  }

  return elements;
}

这篇关于将本机拆分字符串分解为多个文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆