Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_this2.pressRow is not a function

I am trying to learn React Native and am currently trying to create a list view. The everything is loading fine, this issue comes on the press of a row where I get the following error.

enter image description here

I come from a web and objective-c background so this is taking a little time to sink in. This is the code Im 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',
  }
});
like image 959
ORStudios Avatar asked Feb 05 '23 14:02

ORStudios


1 Answers

As mentioned in the comments and above, you need to bind your ES6 class methods with this if you want access to the this variable in other methods, as they do not autobind.

I would suggest putting all the bindings in your constructor, as it is considered good practice (reduce garbage collection) and makes your code neater. See the relevant ESLint page for more information.

constructor(props) {
    super(props);

    ...

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

You can then just use this._renderRow on its own within your class without worrying about binding.

like image 195
Irvin Lim Avatar answered Feb 08 '23 15:02

Irvin Lim