我可以在React-native中单独更改ListView.Datasource中的行吗?

时间:2017-03-11 18:08:49

标签: react-native

我想知道是否可以在React-native中单独更改ListView.Datasource对象中的行?如何单独访问某些特定行?

我认为以下代码可以帮助您了解我的问题!请看看!

(请考虑:我猜测访问DataSource中的行为:myDataSource [4])

以下是我尝试的代码:

class UnderstandDataSource extends Component {
  // Initialize the hardcoded data
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([
        'row 0', 'row 1', 'row 2', 'row 3', 'row 4', 'row 5', 'row 6', 'row 7'
      ])
    };
    this.state.dataSource[4] = ('New row 3'); // I gussed accessing data in an D.S. as dataSource[4]
  }
  render() {
    return (
      <View style={{flex: 1, paddingTop: 22}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text>{rowData}</Text>}
        />
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

如果您想实际更改数据,则应使用新数据重置整个数据源。

如果这仅仅是为了显示目的,那么您应该使用renderRow根据行索引显示不同的视图。

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

export default class ModalExample extends Component {

  constructor(props) {
   super(props);
   const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
   this.state = {
     dataSource: ds.cloneWithRows([
       'row 0', 'row 1', 'row 2', 'row 3', 'row 4', 'row 5', 'row 6', 'row 7'
     ])
   };
  //  this.state.dataSource[4] = ('New row 3'); // I gussed accessing data in an D.S. as dataSource[4]
 }
 render() {
   return (
     <View style={{flex: 1, paddingTop: 22}}>
       <ListView
         dataSource={this.state.dataSource}
         renderRow={(rowData, section, row) => {
           if (row == 3) {
             return (
               <Text>New Row 3</Text>
             )
           } else {
             return (
               <Text>{rowData}</Text>
             )
           }
         }}
       />
     </View>
   );
 }
}