SectionList获取renderSectionHeader中的section index

Ave*_*235 7 react-native react-native-sectionlist

<SectionList
  sections={[{ data: [1, 2] }, { data: [3, 4] }]}
  renderItem={({ item, index }) => ...}
  renderSectionHeader={({ section, index }, i) => {
    console.log(index, i); // both undefined
  }}
/>
Run Code Online (Sandbox Code Playgroud)

我想得到该部分的索引renderSectionHeader.
例如.index应该是0时section.data[1, 2]1时section.data[3, 4].

除了为sections数据添加索引之外,我该如何实现这一目标?

dig*_*git 13

反应原生的SectionList中没有renderSectionHeader的部分索引,但是你可以为你的部分添加索引支柱

 sections={[{ data: [1, 2], index:0 }, { data: [3, 4], index:1 }]}
Run Code Online (Sandbox Code Playgroud)

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

 renderSectionHeader={({section}) => {
     console.log(section.index); 
 }}
Run Code Online (Sandbox Code Playgroud)

  • 如果需要动态添加索引,只需将其映射进去即可。`&lt;SectionListsections={sections.map((section,index)=&gt;({...section,index}))}/&gt;` (3认同)

小智 6

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

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

希望这可以帮助。