简体   繁体   中英

I am trying to auto focus to the next text input on submit

I am rendering text inputs for player names by mapping the components and passing down the player number. I want the user to hit enter and the screen to focus on the next input.

I've tried this

<TextInput style={styles.nameBox} placeholder="Enter Name" onChangeText={(text) => this.setState({text})} ref={`input-${this.props.number}`}
  onSubmitEditing={value => {
   this.setState({ value })
   if (value) this.refs.input_2.focus();
}} />

The problem is that I cant hardcode input_2 because it will then be that way for all of my inputs. I want it to focus on "input-this.props.number++", Basically the following input.

You could develop a function to be triggered on return, and pass the id of the input type that you want to get focus as an argument.

The following sample code is written by Aung Myint Thein from medium.com :

//sample text fields

<TextField
  label={"Field 1"}
  blurOnSubmit={ false }
  returnKeyType={ 'next' }
  onSubmitEditing={() => { this.focusTheField('field2'); }}
/>
<TextField
  ref={input => { this.inputs['field2'] = input }}
  label={"Field 2"}
/>

//function

// variable to hold the references of the textfields
inputs = {};
 // function to focus the field
focusTheField = (id) => {
   this.inputs[id].focus();
}

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM