在TextInput
中输入文字后
我想知道TextInput
中的当前行数。
要么
当前的strings
数也是可以的。
我尝试过string.split('\n').length
,但是当文本大于屏幕时,此代码无法检测到行自动增加。
我如何获得行数
当我在Swift
中进行此功能时
使用string.enumerateLines
函数实现。
您有类似的功能吗?
答案 0 :(得分:2)
据我所知,尚无官方方法来获取当前使用的行数,但我为您提供了一种解决方法:
我们使用onLayout
的{{1}}方法,并跟踪当前使用的高度。我们需要两个状态变量:
TextInput
onLayout:
this.state = {
height: 0, // here we track the currently used height
usedLines: 0,// here we calculate the currently used lines
}
渲染方法
_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});
}
}
工作示例:
答案 1 :(得分:0)
对于本机版本> = 0.46.1
您可以使用onContentSizeChange来获得更准确的线迹,例如,使用具有以下反应的钩子:
/**
* 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<TextInputContentSizeChangeEventData>) => {
// 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 (
<View style={styles.container}>
<TextInput
multiline
style={{backgroundColor: 'green'}}
onContentSizeChange={_onContentHeightChange}
/>
</View>
);
}