React Native split string into multiple text tags

2019-08-11 11:47发布

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?

for example:

"paragraph1...

paragraph2...."

into:

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

2条回答
该账号已被封号
2楼-- · 2019-08-11 12:21

You could look at react-native-parsed-text (https://github.com/taskrabbit/react-native-parsed-text)

It might be a bit more than you need, but you can easily match on the newline character and render a new component for each line

查看更多
小情绪 Triste *
3楼-- · 2019-08-11 12:27

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

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;
}
查看更多
登录 后发表回答