0

I am trying to navigate to another screen using react-navigation. However with this code I get the error: undefined is not an object (evaluation 'this.props.navigation')

When invoking navigatedirectly (see example at the bottom) it works.

What am I doing wrong?

This does not work:

  _renderRow (rowData) {
    return (
      <View >
        <TouchableHighlight onPress={this._handlePress} underlayColor='white'>
            <Image
              style={{width: 50, height: 50}}
              source={{uri: 'http://openweathermap.org/img/w/' + rowData.iconName + '.png'}}
            />
        </TouchableHighlight>
      </View>
    )
  }

  _handlePress () {
    this.props.navigation.navigate('Details')
  }

This does work:

  _renderRow (rowData) {
    return (
      <View >
        <TouchableHighlight onPress={() => this.props.navigation.navigate('Details')} underlayColor='white'>
            <Image
              style={{width: 50, height: 50}}
              source={{uri: 'http://openweathermap.org/img/w/' + rowData.iconName + '.png'}}
            />
        </TouchableHighlight>
      </View>
    )
  }
1
  • 1
    onPress={this._handlePress.bind(this)} Commented Sep 27, 2017 at 23:25

1 Answer 1

1

You need to bind the context. onPress={this._handlePress.bind(this)} will do the work.

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

Here's the documentation:

Handling events

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.