我正在开发一个小应用程序来猜测单词。我想提供有关该单词有多少个字符的线索,而不是单个 TextInput
,甚至可能从一些已经显示的字符开始。
为此,我为每个字符创建一个 TextInput
,然后使用 autofocus=true
设置第一个 TextInput。
我需要的是,当用户在当前 TextInput
中输入一个字符时,焦点会跳转到下一个。
为了创建输入,我为每个键分配一个连续的整数,并将该键传递给函数handleKeyPress
。我在这个函数中需要的是重点关注键等于 i+1 的 TextInput
。
我的代码:
handleKeyPress(i, input_text) {
// Here I need to focus the TextInput with key===(i+1)
const text = this.state.text;
text[i] = input_text;
this.setState({
text: text,
});
}
render() {
let ToRender = [];
let n= 5; // number of characters
// First Input has autofocus set to true
ToRender.push(
<TextInput
key={0}
size="1"
autofocus={true}
value={this.state.text[0]}
onChangeText={(text) => this.handleKeyPress(0, text)}
/>
);
// generate the rest of the Inputs
for (let i=1; i<n; i++) {
ToRender.push(
<TextInput
key={i}
size="1"
value={this.state.text[i]}
onChangeText={(text) => this.handleKeyPress(i, text)}
/>
);
}
return(
<View style={styles.container}>
{ToRender.map((e) => e)}
</View>
);
}
如何根据关键元素聚焦特定元素?
最佳答案
好的,我成功解决了。
首先,我必须通过字段 ref
而不是 key
引用元素,并使用 this.refs[i].focus() 访问它们
聚焦第 i 个元素:
<TextInput
key={i}
ref={i}
size="1"
autofocus={true}
value={this.state.text[i]}
onChangeText={(text) => this.handleKeyPress(i, text)}
/>
然后在函数handleKeyPress
中我可以这样做:
handleKeyPress(i, input_text) {
this.refs[i+1].focus();
}
关于javascript - 根据其键聚焦特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46366616/