【问题标题】:how to call other functions in flat list render function?如何在平面列表渲染函数中调用其他函数?
【发布时间】:2019-01-05 06:05:58
【问题描述】:

我有一个Flatlist,我在该渲染函数中调用其他函数

   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}
      />
   }

我在this.Item 中返回了一些东西,它们在Flatlist 中呈现得很漂亮,但我不能在this.item 中调用我的组件的其他函数!我什至无法在其中指出this.props.navigation 或任何其他this 关键字。我得到未定义的对象错误。

【问题讨论】:

    标签: javascript android ios typescript react-native


    【解决方案1】:

    当您在 FlatList 组件中使用 this.item 时,您需要将此函数绑定到类,您有 3 种主要方法可以做到这一点:

    • 在你的构造函数中:

      contructor(props) {
          this.item = this.item.bind(this);
          // when using this.item everywhere, this will refer to the class in the method
      }
      
    • 如果您使用的是实验性的公共类字段语法,您可以使用类字段来正确绑定回调:

      item = (data) => {
        //now this refer to the class
      }
      
    • 或者直接在组件中:

      <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}
      />
      

    我更喜欢第二种方式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-18
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 2021-10-06
      相关资源
      最近更新 更多