2017-09-22 47 views
1

我正在开发一个小应用程序来猜测一个词。我想给出关于这个词有多少个字符的线索,甚至可能从已经显示的一些字符开始。把焦点放在一个特定元素上

为此,我为每个字符创建一个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

好吧,我设法解决它。

首先,我必须由场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(); 
} 
相关问题