ReactNative这个值在ListView的renderRow中返回不同

时间:2016-02-03 23:33:40

标签: react-native

我试图在ListView中按下一行时调用一个简单的函数。

问题是,thisConstructor函数中返回render,而this中的renderRow返回DedicatedWorkerGlobalScope

所以我得到_this2._onPress is not a function错误。

这是我的全班。

/**
 * Galleries
 */
'use strict';

import React, { PropTypes } from 'react-native'
var {
  ListView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableNativeFeedback,
  View,
} = React;

import GLOBAL from '../FtGlobals';
import GalleryThumb from './GalleryThumb';

/**
 * Styles
 */
var styles = StyleSheet.create({
  list: {
    justifyContent: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
});

/**
 * Module
 */
var Galleries = React.createClass({
  /**
   * States
   */
  componentDidMount: function () {
    this._data = [];
    this.loadNextPage();
  },

  getInitialState: function() {
    return {
      dataSource: new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
      }),

      canLoadMore: true,
      isLoadingContent: false,
    };
  },

  updateDataSource: function(data){
    this._data = this._data.concat(data);
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(this._data),
      isLoadingContent: false,
    })
  },

  loadNextPage: function(){
    if (this.state.isLoadingContent) {
      return;
    }

    this.setState({
      isLoadingContent: true,
    });

    console.log('fetching galleries');
    var url = GLOBAL.API_BASE+'/gallery/list-json';

    fetch(url)
      .then(res => res.json())
      .then(res => this.updateDataSource(res))
  },

  _onPress: function(){
    console.log('test');
  },

  /**
   * Post
   */
  _renderRow: (gallery) => {

    console.log(this._onPress); // returns undefined

    var url = GLOBAL.DYNAMIC_IMG_BASE+'/150x150/'+gallery.cover;
    var title = gallery.title_en;
    return (
      <TouchableNativeFeedback
          onPress={() => this._onPress()}
          background={TouchableNativeFeedback.Ripple()}>
        <View>
          <GalleryThumb url={url} title={title} />
        </View>
      </TouchableNativeFeedback>
    )
  },

  /**
   * Render
   */
  render () {

    console.log(this._onPress); // returns function

    return (
      <ListView contentContainerStyle={styles.list}
        dataSource={this.state.dataSource}
        renderRow={this._renderRow}
        pageSize={100}
      />
    )
  }
})

module.exports = Galleries

感谢。

1 个答案:

答案 0 :(得分:2)

尝试像这样编写renderRow:

_renderRow: function(gallery) {
  console.log(this._onPress); 
  ...
},

或者像这样:

_renderRow(gallery) {
    console.log(this._onPress); 
    ...
},