如何获取 TextInput 字符串中的当前行数? [英] How to get the current number of lines in String of TextInput?
问题描述
在TextInput
中输入文字后我想知道 TextInput
中的当前行数.或者strings
的当前数量也是可能的.
After entering text in TextInput
I want to know the currunt number of lines in TextInput
.
Or
The current number of strings
is also possible.
我已经尝试过 string.split('\n').length
,但是这段代码没有检测到当文本大于屏幕时该行会自动递增.
I've tried string.split('\n').length
, but this code does not detect that the line is automatically incremented when the text is larger than the screen.
如何获取行数
当我在 Swift
中创建此功能时使用 string.enumerateLines
函数实现.
When I make this feature in Swift
Implemented using the string.enumerateLines
function.
你有类似的功能吗?
推荐答案
据我所知,目前没有官方的方法可以获取当前使用的行数,但我有一个解决方法:
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:
我们使用 TextInput
的 onLayout
方法并跟踪当前使用的高度.我们需要两个状态变量:
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() {
console.log('usedLines', this.state.usedLines);
return (
<View style={styles.container}>
<TextInput multiline style={{backgroundColor: 'green'}} onLayout={(e)=> this._onLayout(e)} />
</View>
);
}
工作示例:
https://snack.expo.io/B1vC8dvJH
这篇关于如何获取 TextInput 字符串中的当前行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!