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

前端 未结 2 1156
無奈伤痛
無奈伤痛 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:07

    For react-native version >= 0.46.1

    You can use onContentSizeChange for a more accurate line track, for example with react hooks as following:

         /**
         * used to tracker content height and current lines
         */
        const [contentHeightTracker, setContentHeightTracker] = useState<{
            height: number,
            usedLines: number;
        }>({
            height: 0,
            usedLines: 0
        });
    
        useEffect(() => {
            // console.log('used line change : ' + lineAndHeightTracker.usedLines);
            // console.log('props.extremeLines : ' + props.extremeLines);
            if (contentHeightTracker.usedLines === props.extremeLines) {
                if (extremeHeight.current === undefined) {
                    extremeHeight.current = contentHeightTracker.height;
                }
            }
            //callback height change
            if (contentHeightTracker.height !== 0) {
                props.heightChange && props.heightChange(contentHeightTracker.height,
                    contentHeightTracker.usedLines >= props.extremeLines,
                    extremeHeight.current);
            }
        }, [contentHeightTracker]);
    
        const _onContentHeightChange = (event: NativeSyntheticEvent) => {
            // console.log('event height : ', event.nativeEvent.contentSize.height);
            // console.log('tracker height : ', lineAndHeightTracker.height);
            // the height increased therefore we also increase the usedLine counter
            if (contentHeightTracker.height < event.nativeEvent.contentSize.height) {
                setContentHeightTracker({
                    height: event.nativeEvent.contentSize.height,
                    usedLines: contentHeightTracker.usedLines + 1
                });
            } else {
                // the height decreased, we subtract a line from the line counter
                if (contentHeightTracker.height > event.nativeEvent.contentSize.height) {
                    setContentHeightTracker({
                        height: event.nativeEvent.contentSize.height,
                        usedLines: contentHeightTracker.usedLines - 1
                    });
                }
            }
        };
    
    render() {
        console.log('usedLines', this.state.usedLines);
        return (
          
            
          
        );
      }
    

提交回复
热议问题