How to get the current number of lines in String of TextInput?

前端 未结 2 1142
無奈伤痛
無奈伤痛 2021-01-15 17:28

After entering text in TextInput I want to know the currunt number of lines in TextInput. Or The current number of strings is also pos

2条回答
  •  一生所求
    2021-01-15 18:10

    As far as I know, there is no offical way to get the currently used number of lines, but I have a workaround for you:

    We make use of the onLayout method of our TextInput and we keep track of the currently used height. We need two state variables:

    this.state = {
          height: 0, // here we track the currently used height
          usedLines: 0,// here we calculate the currently used lines 
        }
    

    onLayout:

      _onLayout(e) {
         console.log('e', e.nativeEvent.layout.height);
         // the height increased therefore we also increase the usedLine counter
         if (this.state.height < e.nativeEvent.layout.height) {
             this.setState({usedLines: this.state.usedLines+1}); 
         } 
         // the height decreased, we subtract a line from the line counter 
         if (this.state.height > e.nativeEvent.layout.height){
             this.setState({usedLines: this.state.usedLines-1}); 
         }
         // update height if necessary
         if (this.state.height != e.nativeEvent.layout.height){
             this.setState({height: e.nativeEvent.layout.height});
         }
    
      }
    

    Render Method

      render() {
        console.log('usedLines', this.state.usedLines);
        return (
          
             this._onLayout(e)} />
          
        );
      }
    

    Working Example:

    https://snack.expo.io/B1vC8dvJH

提交回复
热议问题