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:
I am getting the following errors:
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!
source to share
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)
.
source to share