简体   繁体   English

React Native 限制字符

[英]React Native limit characters

I am working with the API.我正在使用 API。

renderGridItem = (itemData) => {
 return(
  <Text>
   {itemData.item.description}
  </Text>
 );
};

I want to show only the first 50 characters of the description.我只想显示描述的前 50 个字符。 How can I do that?我怎样才能做到这一点?

You can just use regular javascript functions to do that.你可以使用常规的 javascript 函数来做到这一点。 In this case substring在这种情况下substring

renderGridItem = (itemData) => {
 return(
  <Text>
   {itemData.item.description.substring(0, 50)}
  </Text>
 );
};

Welcome @Nai to StackOverflow,欢迎@Nai 来到 StackOverflow,

You may use the pure JavaScript functions.您可以使用纯 JavaScript 函数。 slice or maybe substring . slice或者可能substring

Use of Slice:-切片的使用:-

renderGridItem = (itemData) => {
 return(
  <Text>
   {itemData.item.description.slice(0, 50)}
  </Text>
 );
};

Not exactly 50 characters, but you could achieve this with a combination of:不完全是 50 个字符,但您可以通过以下组合来实现:

  • Declare numberOfLines prop for text and set it to 1 / 2 (depending on your needs).为文本声明numberOfLines属性并将其设置为 1 / 2(取决于您的需要)。
  • Declare ellipsizeMode with whatever you want it to be.用你想要的任何东西声明ellipsizeMode
  • Set width of the container / text itself to the width you need and want to display.将容器/文本本身的宽度设置为您需要并希望显示的宽度。

Link to docs on Text in React Native.链接到有关 React Native 中文本的文档。

This way you're making sure that your text is going to show correctly and no word is going to be cut in an ugly way.这样,您可以确保您的文本将正确显示,并且不会以丑陋的方式剪切任何单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM