简体   繁体   中英

Identifying react-native TextInput instance in callback

I'm trying too create a view that takes in a 6 digit verification coder using 6 separate 1 digit TextInput instances. I want to assign a callback to each input so I can track the user inputting the code but I can't see any obvious way to do this.

I can see a onChangeText prop but this doesn't have a way of identifying which of the six TextInputs is calling it.

I'm sure there is an easy way to do this but it's not obvious to me so I appreciate any help.

If you used an onChangeText prop you could call an arrow function inside, call your desired callback, passing the 'id' of the input + the value.

Something like this:

<TextInput onChangeText={(text) => {
  this.yourCallback(text, 1); // 1 is the id of the input.
 }
/>

I haven't tested this, but with a few tweaks, it should solve your problem:

this.state = {
    code: []
}

onChangeText = (text, i) => {
    const code = this.state.code
    if (!Number.isNaN(text)) {
        this.setState({
            code: [...code.slice(0, i), +text, ...code.slice(i + 1)]
        })
    }
}

render(){
    return(
        {Array.from({length: 6}, (_, i) => {
            return (
                <TextInput value={this.state.code[i]} onChangeText={text => this.onChangeText(text, i)} />
            )
        })}
    )
}

Because of the different behavior of default JS classes like Array in the JS Engine V8 used in Chrome (for example) and the one used in React Native (JavaScriptCore), Array.from might behave differently in your app. If you are already using lodash or underscore in your project, I suggest you use lodash.range(6).map((i) => <TextInput ... />) instead.

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