【问题标题】:SectionList get section index in renderSectionHeaderSectionList 获取 renderSectionHeader 中的节索引
【发布时间】:2018-10-22 17:03:53
【问题描述】:
<SectionList
  sections={[{ data: [1, 2] }, { data: [3, 4] }]}
  renderItem={({ item, index }) => ...}
  renderSectionHeader={({ section, index }, i) => {
    console.log(index, i); // both undefined
  }}
/>

我想获取renderSectionHeader中的部分索引。
例如。当section.data[1, 2]index 应为0,当section.data[3, 4] 时为1。

除了将索引添加到sections 数据之外,我还能如何做到这一点?

【问题讨论】:

    标签: react-native react-native-sectionlist


    【解决方案1】:

    React Native 的 SectionList 中没有 renderSectionHeader 的部分索引,但您可以像这样向您的部分添加索引道具

     sections={[{ data: [1, 2], index:0 }, { data: [3, 4], index:1 }]}
    

    然后像这样访问renderSectionHeader中的索引

     renderSectionHeader={({section}) => {
         console.log(section.index); 
     }}
    

    【讨论】:

    • 你拯救了我的一天!!需要自定义索引!!谢谢。
    • 这对于包含一个部分的任何数据非常有用。
    • 如果我们的部分是动态的并且我们无法对索引进行硬编码怎么办?
    • 我同意@PulkitSharma,如果我们的数据是动态的怎么办?它;不会工作。这不是一个好的解决方案。
    • 如果需要动态添加索引,直接映射进去即可。&lt;SectionList sections={sections.map((section, index) =&gt; ({ ...section, index }))} /&gt;
    【解决方案2】:

    我知道现在已经晚了,但也许它可以帮助某人。更好的方法是从传递给 SectionList 组件的数组中获取节的索引。 例如假设你有dataList作为数组传递给sections={dataList},那么你可以得到如下索引:

    renderSectionHeader={({ section }) => {
        const index = dataList.indexOf(section)
        // Here you have the index
        return <View />
    }}
    

    希望这会有所帮助。

    【讨论】:

    • 这不是一个好的解决方案,因为您使用的是indexOf ,这意味着额外的搜索效率不高。
    猜你喜欢
    • 2019-03-05
    • 1970-01-01
    • 2011-08-20
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多