问题描述
我正在尝试使用 Flatlist
或 ScrollView
(我都试过)来实现轮播。旋转木马是 TextInputs
的复合体。
我想要完成的是:
There are 4 TextInputs.
when user type 6 digits on the first input,it automatically scrolls to the second and auto-focus the second input.
when the user type 6 digits on the second,it automatically scrolls to the third and auto-focus the third input.
etc...
the user must be enable to swipe back and change the TextInputs without being focused on other input as he types in something.
我已经在 onScroll
的 ScrollView
事件中尝试了 switch case。
解决方法
听起来您需要使用 Flatlist's scrollToItem 或 scrollToOffset 方法和 TextInput's focus method,然后在每个文本输入更改时监听它。
...
handleInput = (event) => {
// calculate next position based on input text
const nextPosition = this.getNextPosition(event);
this.scrollViewRef.scrollToItem(nextPosition);
/**
* or if you can calculate the exact next pixel offset for the desired
* item based on its dimensions:
*
* this.scrollViewRef.scrollToOffset(nextPosition);
**/
const { name } = event.target.dataset;
const { text } = event.target;
if (name === 'textInput1' && text.length === 6) {
this.textInput2Ref.focus();
} else if (name === 'textInput2' && text.length === 6) {
this.textInput3Ref.focus();
} else if (/*...*/) {
/*...*/
}
}
...
render() {
<View>
<TextInput
data-name={'textInput1'}
ref={(ref) => this.textInput1Ref = ref}
onChange={this.handleInput}
/>
<TextInput
data-name={'textInput2'}
ref={(ref) => this.textInput2Ref = ref}
onChange={this.handleInput}
/>
{/*...TextInput3,4,etc.*/}
<FlatList ref={(ref) => this.scrollViewRef = ref}/>
</View>
}