我正在开发一个小应用程序来猜测一个单词。而不是单TextInput
我想提供关于这个词有多少个字符的线索,甚至可能从已经显示的一些字符开始。
要做到这一点,我为每个角色创建一个TextInput
,然后我将第一个TextInput设置为autofocus=true
。
我需要的是当用户在当前TextInput
输入一个角色时,焦点跳转到下一个角色。
要创建输入,我为每个键分配一个连续的整数,并将此键传递给函数handleKeyPress
。我在这个函数中需要的是将TextInput
的焦点等于i + 1。
我的代码:
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>
);
}
如果给定关键字,我如何关注特定元素?
答案 0 :(得分:0)
好的,我设法解决了。
首先,我必须按字段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();
}