I create a <FlatList />
include <Text />
, i want to click each of the <Text />
can change this.state
.
But when i click it that will show error:
this.setState is not a function
Why?
Here is my <FlatList />
:
render() {
return (
<View>
<FlatList
ListHeaderComponent={() => (
!cityArray.length ? (
<View style={{ height: 300 }}>
<Text style={styles.sectionTitle}>
Show empty message...
</Text>
</View>) : null
)}
data={cityArray}
renderItem={this.renderItem}
horizontal={true}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
Here is my renderItem
function: onPress
will shows the error
renderItem({ item }) {
return (
<View style={styles.headerView}>
<TouchableOpacity
onPress={() => {
this.setState({ test: 'test press' });
}}
>
<Text>{item.cnCity}</Text>
</TouchableOpacity>
</View>
);
}
My this.state:
constructor(props) {
super(props);
// this.renderRow = this.renderRow.bind(this);
this.state = { tickets: [], selectedOption: '', theaters: [], test: '' };
}
I try to creat another function:
testPress = () => {
this.setState({ test: 'test function' });
}
and use it like:
renderItem({ item }) {
return (
<View style={styles.headerView}>
<TouchableOpacity
onPress={() => {
this.testPress();
}}
>
<Text>{item.cnCity}</Text>
</TouchableOpacity>
</View>
);
}
It still shows the same error. Why? I can't figure it out.
Any help would be appreciated.