Use if in onPress event

Asked

Viewed 411 times

0

I’m trying to use a if thus:

<Button
      iconRight={{
        name: 'search',
        type: 'font-awesome'
      }}
      title='BUSCAR'
      buttonStyle={{
        marginTop: 15,
        borderRadius: 7,
        backgroundColor:'#2C5CAA'
      }}
      onPress={(function() {if (this.state.busca.length > 0){
        alert(this.state.busca.length);
      }else{
        this.props.navigation.navigate('Lista', {
                                                              busca: this.state.busca,
                                                              city: this.state.city })}
      })
    }
     />

However, I am getting an error in the variable this.state.busca:

Undefined is not an Object (evaluating 'this.state.busca')

How to solve?

  • Sorry I didn’t enter the full code, it’s a button. I changed the question @wmsouza

  • What is the content of this.state.busca the good thing would be you create a snack

  • Probably the context of this is for the anonymity function within the onPress(), you need to bind in the context of your class to be able to access the state of the component

1 answer

0

Most likely in this.state.busca the this is linked to the context of its anonymous function within the onPress() try to make a bind() to pass the context of your class to the this:

<Button

  iconRight={{
    name: 'search',
    type: 'font-awesome'
  }}

  title='BUSCAR'

  buttonStyle={{
    marginTop: 15,
    borderRadius: 7,
    backgroundColor:'#2C5CAA'
  }}

  onPress={(function() {
    if (this.state.busca.length > 0){
        alert(this.state.busca.length);
    } else {
        this.props.navigation.navigate('Lista', {
            busca: this.state.busca,
            city: this.state.city 
        })
    }
  }).bind(this)

} />

I recommend that you isolate this function elsewhere in your code so that it is more readable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.