2017-09-22 12 views
1

単語を推測するための小さなアプリケーションを開発しています。単一の文字の代わりに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

私はそれを解決することができました。私にできる機能handleKeyPress内で次に

<TextInput 
    key={i} 
    ref={i} 
    size="1" 
    autofocus={true} 
    value={this.state.text[i]} 
    onChangeText={(text) => this.handleKeyPress(i, text)} 
/> 

まず、私は、フィールドの代わりにkeyrefによって要素を参照し、i番目の要素を集中するthis.refs[i].focus()を使用してそれらにアクセスする必要が

handleKeyPress(i, input_text) { 
    this.refs[i+1].focus(); 
} 
関連する問題