_this2.pressRow is not a function

I am trying to learn React Native and am currently trying to create a list view. Everything loads fine, this problem occurs when I press a line where I get the following error.

enter image description here

I am coming from a website and objective-c background so it takes a little time for this. This is the code I am using for the screen.

import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight
} from 'react-native'

export default class FeedView extends Component {

  static navigationOptions = {
    title: 'Chat with Feed',
  };

  constructor() {
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(['row 1', 'row 2']),
    };
  }

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderRow}
        />
      </View>
    );
  }

  _renderRow( rowData: string, sectionID: number, rowID: number, highlightRow: (sectionID: number, rowID: number) => void ){
    return (
      <TouchableHighlight onPress={() => {
          this._pressRow(rowID);
          highlightRow(sectionID, rowID);
        }}>
        <View>
          <View style={styles.row}>
            <Text style={styles.text}>Testing</Text>
          </View>
        </View>
      </TouchableHighlight>
    );
  }

  _pressRow( rowID: number ){

  }

}

var styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    padding: 10,
    backgroundColor: '#F6F6F6',
  }
});

      

+3


source to share


2 answers


As mentioned in the comments and above, you need to bind the methods of the ES6 class with this

if you want to access the variable this

in other methods, since they are not autobind.

I would suggest putting all the bindings in your constructor as it is considered good practice (reduce garbage collection) and will make your code cleaner. For more information see the related ESLint page .



constructor(props) {
    super(props);

    ...

    this._renderRow = this._renderRow.bind(this);
    this._pressRow = this._pressRow.bind(this);
}

      

Then you can just use it this._renderRow

yourself in your class without worrying about binding.

+4


source


The problem is that this

in your function renderRow

does not refer to context of the React Component

and therefore you cannot access the function_pressRow

You need to bind a function renderRow



render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <ListView
            dataSource={this.state.dataSource}
            renderRow={() => this._renderRow()}
        />
      </View>
    );
  }

      

+1


source







All Articles