oij*_*djn 3 react-native react-native-textinput
在中输入文本后,TextInput
我想知道 中当前的行数TextInput。或者当前的数量strings也是可以的。
我已经尝试过了string.split('\n').length,但是此代码没有检测到当文本大于屏幕时该行会自动递增。
如何获取行数
当我使用函数Swift
实现此功能时string.enumerateLines。
你们有类似的功能吗?
据我所知,没有官方方法可以获取当前使用的行数,但我为您提供了一个解决方法:
我们使用onLayout我们的方法TextInput并跟踪当前使用的高度。我们需要两个状态变量:
this.state = {
height: 0, // here we track the currently used height
usedLines: 0,// here we calculate the currently used lines
}
Run Code Online (Sandbox Code Playgroud)
布局上:
_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});
}
}
Run Code Online (Sandbox Code Playgroud)
渲染方法
render() {
console.log('usedLines', this.state.usedLines);
return (
<View style={styles.container}>
<TextInput multiline style={{backgroundColor: 'green'}} onLayout={(e)=> this._onLayout(e)} />
</View>
);
}
Run Code Online (Sandbox Code Playgroud)
工作示例:
https://snack.expo.io/B1vC8dvJH
| 归档时间: |
|
| 查看次数: |
5208 次 |
| 最近记录: |