简体   繁体   English

如何比较numberOfLines道具值 <Text> 与数据行数有关?

[英]How to compare numberOfLines props value in <Text> with number of line from data?

I need your help for my code. 我的代码需要您的帮助。 I have a screen that require read more and read less button. 我的屏幕需要阅读更多和阅读更少的按钮。 But if the data is only a few words, the button must not rendered. 但是,如果数据只有几个字,则不得渲染按钮。

I have a return data from backend with this format: 我从后端返回的数据具有以下格式:

data: "1. this is just an example of free text, I'm typing this on Friday \r\n 2. I like seafood. I want to go to beach right now \r\n\ 3. I need holidays, I need a long holidays \r\n\ 4. Hello World, this is a dummy data \r\n\ 5. How to solve this problem? \r\n\ 6. Help me please \r\n\ 7. Thank you"

I want to apply 'read more' and 'read less'. 我想申请“多读”和“少读”。 so I did this: 所以我这样做:

state = { readMore: false }
render() {
  return (

  // Some code

  <Text style={styles.textContent} numberOfLines={readMore? null : 5}>
    {data}
  </Text>
  <TouchableOpacity
    onPress={this.setState({ readMore: !this.state.readMore})} 
    style={{ paddingTop: 4 }}>
       {readMore ? (
          <Text style={styles.readMoreStyle}>read less</Text>
       ) : (
          <Text style={styles.readMoreStyle}>read more</Text>
       )}
   </TouchableOpacity>
)}

I set numberOfLines to 5 for default. 我默认将numberOfLines设置为5。 And will show all data if user clicked read more and will show 5 lines if user clicked read less. 并且如果用户单击了“ read more”,将显示所有数据;如果用户单击了“ readless”,则将显示5行。

I tried to console the data's number of lines using this method: 我试图使用此方法来控制数据的行数:

const thisData = data
const test = `${thisData.split(/\r\n|\r|\n/).length}`;
console.log(test)

if I use the dummy data above, the console will return 7. When I use numberOfLines props in it's different. 如果我使用上面的虚拟数据,则控制台将返回7。当我使用numberOfLines道具时,它会有所不同。 It will render each line of my data, but when one line is too long, it will move to the second line to fit the screen. 它将呈现我数据的每一行,但是当一行太长时,它将移至第二行以适合屏幕。 And read it as 2 lines. 并读为2行。

Example, first line of my data is: "Hello, this is just a text. Please help me to solve this problem. I am new in react-native, so I need your experience" 例如,我的数据的第一行是:“您好,这只是文本。请帮助我解决此问题。我是react-native的新手,所以我需要您的经验”

it is too long, in iPhone 5s will render it in maybe 3 lines. 它太长了,在iPhone 5s中可能会以3行显示。

How I set logic to show button read more only if the data is less than 5 lines (numberOfLines={5}) 我如何设置逻辑以仅在数据少于5行(numberOfLines = {5})时显示按钮读取更多内容

Thanks 谢谢

numberOfLines={readMore? null : screenSizeValue}

一种想法是计算屏幕尺寸并相应地调整“ screenSizeValue”。

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

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