简体   繁体   中英

React Native ListView customization

In Swift I can register as many different types of cells as I want for a single UITableView , and simply designate a certain cell at a certain index of row using the delegate method like:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) 
-> UITableViewCell {
  if indexPath.row == 0 {
    return cellOfType0;
  }else if indexPath.row == 1 {
    return cellOfType1;
  } ...  
}

How can I do this with React Native?

You can still check for an index if either your item has a unique id, or using the rowID argument to renderRow:

renderRow(rowData, sectionID, rowID, highlightRow) {
    if(rowID === '3')  {
        return <View style={ styles.red } key={ sectionID }>
                 <Text>{ rowData.name }</Text>
                </View>
    }
}

I've set up an example here , and pasted the code below as well.

https://rnplay.org/apps/QCG0pA

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView
} = React;

var data = [ {name: 'Christina'}, { name: 'Allen' }, { name: 'Amanda' }, { name: 'James' },{name: 'Christina'}, { name: 'Allen' }, { name: 'Amanda' }, { name: 'James' } ]

var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

var SampleApp = React.createClass({

  getInitialState(){
    return { dataSource: ds.cloneWithRows(data) }
  },

  renderRow(rowData, sectionID, rowID, highlightRow){
   console.log('rowID', rowID)
    if(rowID === '3')  {
        return <View style={ styles.red } key={ sectionID }>
                 <Text>{ rowData.name }</Text>
                </View>
    } 
    if(rowID === '6')  {
        return <View style={ styles.green } key={ sectionID }>
                 <Text>{ rowData.name }</Text>
                </View>
    }  
    if(rowID % 2 == 0) {
        return <View style={ styles.even } key={ sectionID }>
                 <Text>{ rowData.name }</Text>
                </View>
    }
    return <View style={ styles.normal } key={ sectionID }>
             <Text>{ rowData.name }</Text>
           </View>
  },

  render() {
    return (
      <View style={styles.container}>
        <ListView 
        renderRow={ this.renderRow }
        dataSource={ this.state.dataSource }
        />        
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
   marginTop:60
  },
  normal: {
    height:40,
    backgroundColor: '#ededed'
  },
  even: {
    height:40,
    backgroundColor: 'white'
  },
  red: {
    height:40,
    backgroundColor: 'red'
  },
  green: {
    height:40,
    backgroundColor: 'green'
  }
});

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

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