Reputation: 956
I have a Flatlist
which i call other functions inside that render function
otherFunc(){
alert('some thing')
}
item(data){
return(
//...something..
{this.otherFunc()} <<<<<<<<<problem is here...its undefined
);
}
render() {
<FlatList
ref={ref => this.scrollView = ref}
data={this.state.foods}
extraData={this.state}
keyExtractor={this._keyExtractor}
renderItem={this.Item}
horizontal
onEndReached={(x) => { this.loadMore() }}
onEndReachedThreshold={0.5}
/>
}
i return something in this.Item
which they pretty render in Flatlist
but i can't call other functions of my component inside this.item
! and i even can't point this.props.navigation
or any other this
key word inside that. i get undefined object error.
Upvotes: 2
Views: 3485
Reputation: 138
When you use this.item in the FlatList component you need to bind this function to the class, you have 3 main ways to do that:
in your constructor :
contructor(props) {
this.item = this.item.bind(this);
// when using this.item everywhere, this will refer to the class in the method
}
if you are using the experimental public class fields syntax, you can use class fields to correctly bind callbacks :
item = (data) => {
//now this refer to the class
}
Or directly in the component:
<FlatList
ref={ref => this.scrollView = ref}
data={this.state.foods}
extraData={this.state}
keyExtractor={this._keyExtractor}
renderItem={(data) => this.item(data)}
horizontal
onEndReached={(x) => { this.loadMore() }}
onEndReachedThreshold={0.5}
/>
i prefer the second way
Upvotes: 4