1

I have a listview in index.js my react native project like below.

import ResultRow from './resultRow'

class ResultList extends Component {
    constructor() {

    }

    updateDate(){
        //Some operation
    }

    onPressRow() {
        try {
          console.log("Selected!");

        //Some operation

          this.updateDate(); // Got undefined is not a function

        } catch (error) {      
          console.error(error);
        }
    }

    renderRow(rowData) {
        return (
          <ResultRow
          onPress={this.onPressRow}
            {...rowData} />
        )
      }

    render() {
      return (
              <ListView
                style={[styles.container, { padding: 10, backgroundColor: '#ddd' }]}
                dataSource={this.state.dataSource}
                renderRow={this.renderRow.bind(this)} />
            );
    }

}

And bind list items using this template in resultRow.js file like below.

import React from 'react';
import { TouchableHighlight, StyleSheet, Image,View } from 'react-native';

const ResultRow = (props) => (
  <TouchableHighlight onPress={() => props.onPress()}>
    <View>
      <Text>My Row</Text>       
    </View>
  </TouchableHighlight >
);

export default ResultRow;

If I select a row from list view onPress event called. And onPressRow function is executed. from onPressRow function I called another function which is defined in same class named "updateDate". I call like this this.updateDate(); But got undefined is not a function error.

What I am doing wrong?

Thanks in advance.

bCliks
  • 2,918
  • 7
  • 29
  • 52

1 Answers1

1

You need to bind the function as this doesn't refer to the appropriate context in your code. You can make use of arrow function

onPressRow = () => {
        try {
          console.log("Selected!");

        //Some operation

          this.updateDate(); 

        } catch (error) {      
          console.error(error);
        }
   }

The other way to bind you function is to set the binding in the constructor

constructor() {
   super();
   this.onPressRow = this.onPressRow.bind(this);
}

In fact you will need to bind any function that will make use of this to refer to the context of your react class.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 1
    Your example isn't valid ECMAScript 6. It would be useful to others if you explained what to do in order to gets this (experimental) feature to work. – Felix Kling Jan 19 '17 at 06:24