简体   繁体   中英

how to call other functions in flat list render function?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM