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.
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',
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With