Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Event

I have a TextInput component that calls an 'OnChangeText' event :

<TextInput onChangeText={(text) => this.setState({zip:text})}/>

That works fine.

Now I want to change the call event to a function:

 <TextInput onChangeText={_handleTextChange}/>

_handleTextChange(event) {
       this.setState({zip: 
       event.nativeEvent.text});

  }

That doesn't work. I get the following error :

undefined is not an object (evaluating 'event.nativeEvent.text'

How do send the 'Event' object to _handleTextChange function?

Thanks, Yaron

like image 616
Yaron Avatar asked Dec 10 '22 16:12

Yaron


1 Answers

onChangeText passes a string to your handler function instead of an Event.

class YourComponent {
   render () {
     // ...
     return <TextInput onChangeText={this._handleTextChange.bind(this)}/>;
   }

  _handleTextChange(text) {
     this.setState({zip: text});
  }
}

EDIT

If you want an Event instead of text string, you can use onChange instead of onChangeText.

class YourComponent {
   render () {
     // ...
     return <TextInput onChange={this._handleTextChange.bind(this)}/>;
   }

  _handleTextChange(event) {
     this.setState({zip: event.nativeEvent.text});
  }
}
like image 199
Shuhei Kagawa Avatar answered Jan 11 '23 02:01

Shuhei Kagawa