首页 > 解决方案 > 如何在某些数据部分之后将分隔符添加到 FlatList 中?

问题描述

渲染一些数据后,如何在 React-Native FlatList 中添加分隔符?

我尝试使用 React-Native SectionList,但我无法像在 FlatList 中那样添加 fetchNext 函数。

这是我当前的代码

<FlatList
  data={data}
  keyExtractor={keyExtractor}
  renderItem={renderItem}
  fetchNext={fetchNextPage}
  numColumns={2}
  ItemSeparatorComponent={<View style={this.separatorStyles} />}
  ListFooterComponent={isFetching && <LoaderView notExpand />}
/>

|####| |####|
|####| |####|
|####| |####|

|####| |####|
|####| |####|
|####| |####|
------------- (need add some separator)
|####| |####|
|####| |####|
|####| |####|

|####| |####|
|####| |####|
|####| |####|

标签: iosreact-nativereact-native-flatlist

解决方案


您可以通过修改数据和创建更高级的 renderItem 函数轻松实现此目的。首先,我们从修改数据开始。我使用了以下示例数据:

    data: [
        { id: '1'},{ id: '2'},{ id: '3'},{ id: '4'},{ id: '5'},{ id: '6'},{ id: '7'},{ id: '8'},{ id: '9'},{ id: '10'}
    ]

现在我们修改一下,解释见代码注释:

modifyData(data){
    const numColumns = 2; // we want to have two columns
    const separator = 4;  // after 4 elements we want to have a separator 
    var tmp = []; // temporary array to store columns
    var newData = [];
    data.forEach((val, index) => {
      // check if column is full, if yes push it to the new array
      if (index % numColumns  == 0 && index != 0){
        newData.push(tmp);
        tmp = [];
      }
      // inject separator element if necessary, we mark them with id: -1
      if ( index % separator == 0 && index != 0){
        newData.push({ id: -1 })
      }
       tmp.push(val);
    }); 
    if (tmp.length > 0){
        // add remaining elements
        newData.push(tmp);
    }
   return newData;
  }
  render() {
    // modify your data, afterwards pass it to the FlatList 
    const newData = this.modifyData(this.state.data);
    return (
      <View style={styles.container}>
       <FlatList
        data={newData}
        renderItem={({item, index}) => this.renderItem(item, index)}
       />
      </View>
    );
  }

现在数据看起来像:

    data: [
        [{ id: '1'},{ id: '2'}],[{ id: '3'},{ id: '4'}], {id: -1},[{ id: '5'},{ id: '6'}],[{ id: '7'},{ id: '8'}], { id: -1 },[{ id: '9'},{ id: '10'}]
    ]

现在我们增强 renderItem 函数:

renderItem(item, index){
    // check if the current item is a separator
    if (item.id == -1){
      return (
        <View key={index} style={{flex: 1, flexDirection: 'row', justifyContent: 'center'}}>
            <Text> --------SEPERATOR -------- </Text>
        </View>
      )
    }
    // otherwise loop over array
    const columns = item.map((val, idx) => {
      return (
        <View style={{flex: 1, justifyContent: 'center'}} key={idx}>
          <Text style={{textAlign: 'center'}}> ID: {val.id} </Text>
        </View>
      )
    });
    return (
      <View key={index} style={{flexDirection: 'row', flex: 1}}>
        {columns}
      </View>
    )
  }

输出:

演示

工作示例:

https://snack.expo.io/SJBUZ4i2V


推荐阅读