我有这段代码创建了一堆输入字段(最多可以容纳一个char):
renderInputs() {
var products = []
// some code that generates a randomNumber
for (let p = 0; p < randomNumber; p++){
products.push (<TextInput defaultValue="" maxLength={1} key={p} onChangeText={(text) => this.handleChange(text, p)}></TextInput> );
}
return products
}
每当用户填写一个输入字段时,我希望焦点从一个输入字段自动移动到下一个输入字段
答案 0 :(得分:1)
您需要存储对所有输入的引用。拥有它们,您可以专注于它们中的任何一个。输入内容更改后,您决定是否转到下一个输入。
这是代码,没有运行和测试它编写 - 很可能它包含拼写错误甚至不运行。但这个想法就在那里......
class ParentComponent extends Component {
inputRefs = []
keepInputRef = (index) => {
this.inputRefs[index] = null;
return (ref) => {
this.inputRefs[index] = ref;
}
}
handleChange(text, p) {
// do what you need.
// then...
// NOTE: `if` condition is completely off, won't work... Replace it with condition valid for your needs.
if (something) {
const nextInput = this.inputRefs[p + 1];
if (nextInput) {
nextInput.focus()
}
}
}
renderInputs() {
var products = [];
for (let p = 0; p < randomNumber; p++){
products.push (
<TextInput key={p} ref={this.keepInputRef(p)} defaultValue="" maxLength={1} onChangeText={(text) => this.handleChange(text, p)}></TextInput>
);
}
return products
}
}