有没有一种方法可以在一些数据间隔后在垂直平面列表中实现水平平面列表?

Pet*_*ndi 2 react-native

我正在尝试制作一个平面列表,它可以呈现来自不同 api 的数据,就像 Instagram 所做的那样,包含建议和广告。我想在渲染垂直列表中的几个项目后,在垂直平面列表中渲染水平平面列表。

And*_*rew 5

这是可以做到的。它是关于在外部 FlatList 的 renderItem 函数中处理它的。

FlatList 有两个函数:renderItem 和 keyExtractor。仅当您的物品没有密钥时才需要 keyExtractor,并且它完全可重复使用。因此,您计划渲染的每个不同的 FlatList 都需要一个 renderItem。

所以外部FlatList使用该renderMainItem函数,内部FlatList使用renderHorizontalItem

请注意我是如何设置数据的。每个对象都有一个类型,允许我在函数中应呈现的内容之间切换renderMainItem,返回一行或返回另一个 FlatList。

这是一个显示其工作原理的小吃https://snack.expo.io/S1sPDPAM4

import React from 'react';
import { Text, View, StyleSheet, FlatList, SafeAreaView } from 'react-native';

export default class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      data: [
        { type: 'row', text: 'row 1'},
        { type: 'row', text: 'row 2'},
        { type: 'list', data: ['Apple', 'Banna', 'Pear', 'Orange', 'Grape', 'Pineapple']},
        { type: 'row', text: 'row 3'},
        { type: 'row', text: 'row 4'},
        { type: 'row', text: 'row 5'},
        { type: 'list', data: ['Bike', 'Car', 'Train', 'Plane', 'Boat', 'Rocket']},
        { type: 'row', text: 'row 6'},
        { type: 'row', text: 'row 7'},
        { type: 'row', text: 'row 8'},
      ]
    }
  }

  renderMainItem = ({item}) => {
    if (item.type === 'row') {
      return (
      <View style={styles.mainItem}>
        <Text>{item.text}</Text>
      </View>
      );
    } 

    if (item.type === 'list') {
      return (
        <View style={styles.list}>
        <FlatList
          extraData={this.state}
          data={item.data}
          keyExtractor={this.keyExtractor}
          renderItem={this.renderHorizontalItem}
          horizontal={true}
        />
        </View>
      );
    }
  }

  keyExtractor = (item, index) => {
    return index.toString();
  }

  renderHorizontalItem = ({item}) => {
    return (
      <View style={styles.horizontalItem}>
        <Text>{item}</Text>
      </View>
    );
  }

  render() {
    return (
      <SafeAreaView style={styles.container}>
      <FlatList
        extraData={this.state}
        data={this.state.data}
        keyExtractor={this.keyExtractor}
        renderItem={this.renderMainItem}
      />
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white'
  },
  mainItem: {
    height: 80, 
    justifyContent: 'center', 
    alignItems: 'center', 
    margin: 10, 
    backgroundColor: 'yellow'
  },
  horizontalItem: {
    width: 80, 
    justifyContent: 'center', 
    alignItems: 'center', 
    marginHorizontal:5, 
    backgroundColor: 'blue'
  },
  list: {
    height: 80, 
    marginHorizontal: 5
  }
});
Run Code Online (Sandbox Code Playgroud)

这只是一个简单的示例,展示了创建内部包含水平 FlatList 的 FlatList 的多种方法之一。

  • https://snack.expo.io/B1hgsL1QN 这里对之前的零食略有调整。 (2认同)