如何在React-Native中选择一个ListView项?

时间:2016-07-03 15:05:08

标签: javascript listview react-native

我是React-Native的新手。我想使用ListView选择一个项目。当我第一次按项目时,ListView renderRow()被调用,但毕竟不工作!我该如何解决这个错误?我的问题在哪里?

我在here

中写了一个演示

2 个答案:

答案 0 :(得分:15)

我最初设置了空数据源,然后将其设置为使用componentDidMount中的数据变量进行克隆。然后,在onPressRow方法中,我对数据状态变量的副本进行了必要的更改,然后通过setState方法将其设置回数据。不确定你的问题是什么,但这现在正在发挥作用。

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight
} from 'react-native';

class ListViewDemo extends Component {

  constructor(props) {
    super(props);

    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      data: this._genRow(),
      dataSource: ds,
    }
  }

  componentDidMount() {
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(this.state.data)
    });
  }

  _genRow(){
    var datas = [];
    for (var i = 0; i < 5; i++) {
      datas.push({
        row: i,
        isSelect: false,
      });
    }
    console.log('datas ' + JSON.stringify(datas));
    return datas;
  }

  render() {
    return (
      <ListView
        dataSource = {this.state.dataSource}
        renderRow = {this._renderRow.bind(this)}
        renderHeader = {() => <View style={{height: 10, backgroundColor:     '#f5f5f5'}} />}
        onEndReached = {() => console.log('')}
        renderSeparator = {(sectionID, rowID) =>
          <View
            style={styles.style_separator}
            key={`${sectionID} - ${rowID}`}
          />}
      />
    );
  }

  _renderRow(rowData: string, sectionID: number, rowID: number) {
    console.log('render row ...');
    return (
      <TouchableHighlight onPress={this._onPressRow.bind(this.rowID, rowData)}>
        <View style={styles.style_row_view}>
          <Text style={styles.style_text}>{rowData.row}</Text>
          <Text style={styles.style_text}>{rowData.isSelect ? 'true' : 'false'}                   </Text>
            </View>
          </TouchableHighlight>
        );
      }

  _onPressRow(rowID, rowData) {

    rowData.isSelect = !rowData.isSelect;
    var dataClone = this.state.data;
    dataClone[rowID] = rowData;
    this.setState({
      data: dataClone
    });
    console.log(this.state.data);
  }
}

const styles = StyleSheet.create({
  style_row_view: {
    flex: 1,
    flexDirection: 'row',
    height: 57,
    backgroundColor: '#FFFFFF',
  },
  style_text: {
    flex: 1,
    marginLeft: 12,
    fontSize: 16,
    color: '#333333',
    alignSelf: 'center',
  },

});

AppRegistry.registerComponent('ListViewDemo', () => ListViewDemo);

答案 1 :(得分:-1)

尝试调用这样的函数 onPress = {(obj1,obj2)=&gt; this._onPressRow(rowID,rowData)}