简体   繁体   中英

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. And will show all data if user clicked read more and will show 5 lines if user clicked read less.

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. 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.

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"

it is too long, in iPhone 5s will render it in maybe 3 lines.

How I set logic to show button read more only if the data is less than 5 lines (numberOfLines={5})

Thanks

numberOfLines={readMore? null : screenSizeValue}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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