OnPress error "is not a function" and "is undefined"

Taking my baby first steps towards learning Rect Native and stuck with these errors for a while. When I click on an element:

enter image description here

I am getting the following errors:

enter image description here

Here is my native React code:

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

export default class Component5 extends Component {
  constructor(){
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      userDataSource: ds
    };
    this._onPress = this._onPress.bind(this);
  }

  _onPress(user){
    console.log(user);
  }

  renderRow(user, sectionId, rowId, hightlightRow){
    return(
      <TouchableHighlight onPress={() => {this._onPress(user)}}>
        <View style={styles.row}>
          <Text style={styles.rowText}>{user.name}: {user.email}</Text>
        </View>
      </TouchableHighlight>
    )
  }

  fetchUsers(){
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((response) => {
        this.setState({
          userDataSource: this.state.userDataSource.cloneWithRows(response)
        });
      });
  }

  componentDidMount(){
    this.fetchUsers();
  }

  render() {
    return (
      <ListView
        style={styles.listView}
        dataSource={this.state.userDataSource}
        renderRow={this.renderRow.bind()}
      />
    );
  }
}

const styles = StyleSheet.create({
  listView: {
    marginTop: 40
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'center',
    padding: 10,
    backgroundColor: 'blue',
    marginBottom: 3
  },
  rowText: {
    flex: 1,
    color: 'white'
  }
})

AppRegistry.registerComponent('Component5', () => Component5);

      

Very grateful for any input!

+3


source to share


2 answers


Newbie mistake - forgetting to bind renderRow correctly in a component. I wrote:

renderRow={this.renderRow.bind()}



and it should of course be:

renderRow={this.renderRow.bind(this)}

+2


source


You are trying to link this

in many different places, but for example, renderRow={this.renderRow.bind()}

nothing links. Sometimes you also use arrow syntax.

I would recommend using the arrow syntax for your class methods so that you don't have to bind anymore this

(this is a feature of the arrow style function syntax) i.e.



  • Delete this._onPress = this._onPress.bind(this);

  • Rewrite _onPress

    in_onPress = user => console.log(user);

  • Call him through <TouchableHighlight onPress={() => this._onPress(user)}>

You can do this with all other class methods and will never be used again .bind(this)

.

+1


source







All Articles