React Native: Determine number of lines of Text component

前端 未结 4 1107

As the title says, I\'ve been trying to find a way to determine the number of lines the text component AFTER it has been given text. Look at my example below.



        
4条回答
  •  自闭症患者
    2020-12-06 10:11

    The solution Garrett McCullough have provided seem working for me, and I just want to add some code example:

    import React from 'react';
    import { StyleSheet, Text, View, TouchableHighlight } from 'react-native';
    
    const styles = StyleSheet.create({
        text: {
          fontSize: 24,
          lineHeight: 30,
        }
    });
    
    export default class App extends React.Component {
    
        onLayout = e => {
            const { height } = e.nativeEvent.layout;
            this.count = Math.floor(height / styles.text.lineHeight)
        }
    
        render() {
            return (
                
                  
                    Random text. Random text. Random text. Random text. Random text. Random text. Random text.
                    Random text. Random text. Random text. Random text. Random text. Random text. Random text.
                    Random text. Random text. Random text. Random text. Random text. Random text. Random text.
                    Random text. Random text. Random text. Random text. Random text. Random text.
                  
    
                   alert(`text lines count is ${this.count}`)}>
                    touch me!
                  
                
            );
        }
    }
    

    https://snack.expo.io/@devastr1/text-lines-count-example

提交回复
热议问题