【问题标题】:Put ads in flat list every X items?每 X 项将广告放在平面列表中?
【发布时间】:2018-02-12 08:08:34
【问题描述】:

我有一个包含许多项目的平面列表。是否有可能在每 X 个项目中打破它以将其他组件(例如广告)放入其中?我在官方文档中找不到。这是我的平面列表:

<FlatList
        ListFooterComponent={this.renderFooter}   
        removeClippedSubviews={true}
        data={this.state._data}
        renderItem={({item}) => {
            return (
           <View>
             ...
          {item.something}
              ...
        </View>
         );
          }}
         keyExtractor={(item, index) => index}
        />     

【问题讨论】:

    标签: reactjs react-native react-native-flatlist


    【解决方案1】:

    据我所知,FlatList 中没有内置这样的功能。

    但是,这样做的一种方法是将广告添加到传递给 FlatListdata 并修改 renderItem 函数以使其也能够呈现它们。

    例如以下代码 sn-p 将获取一个内容数组和一个广告数组,并在每 2 个元素之后添加一个 add:

    const ads = [...]; // array of ads
    const content = [...]; // array of content
    const alternate = 2;
    
    const data = content.reduce((acc, curr, i) => {
      if ((i + 1) % alternate === 0) {
        const adIndex = Math.floor(i / alternate) % ads.length;
        return [...acc, curr, {...ads[adIndex], isAdd: true }];
      }
    
      return [...acc, curr];
    }, []);
    

    然后您可以修改renderItem 函数以在项目为一时呈现添加,例如

    ({item}) => {
      if (item.isAdd) {
        // renderAdd
      } else {
        // renderContent
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-29
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多