在 Swift 中,我可以为单个 UITableView
注册尽可能多的不同类型的单元格,并使用委托(delegate)方法简单地指定行的特定索引处的特定单元格,例如:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
if indexPath.row == 0 {
return cellOfType0;
}else if indexPath.row == 1 {
return cellOfType1;
} ...
}
我如何使用 React Native 做到这一点?
最佳答案
如果您的项目具有唯一 ID,或者使用 renderRow 的 rowID 参数,您仍然可以检查索引:
renderRow(rowData, sectionID, rowID, highlightRow) {
if(rowID === '3') {
return <View style={ styles.red } key={ sectionID }>
<Text>{ rowData.name }</Text>
</View>
}
}
我已经设置了一个示例 here ,并粘贴下面的代码。
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);
关于ios - React Native ListView 自定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544822/