遵循RN SectionList文档。如果我要像示例中那样构建同质的节列表:

<SectionList
  renderItem={({item, index}) => <ListItem title={item} index={index} />}
  renderSectionHeader={({section}) => <Header title={section.title} />}
  sections={[ // homogeneous rendering between sections
    {data: [...], title: ...},
    {data: [...], title: ...},
    {data: [...], title: ...},
  ]}
/>

如何使index在各节之间继续?现在是 index reflects the Item's index within the section。对于每个部分,index从零开始。还有什么其他方法可以使索引从第一部分的第一项到最后一部分的最后一项。有什么想法吗?

最佳答案

从RN 0.52版本开始,仅利用SectionList就没有解决方案。
显然,我们可以通过其他方式获得期望的结果。

我成功地使索引从第一部分到最后一部分,通过快速的JS解决方法逐项进行:

  • 创建所有项目的数组
  • 获取与array.find()的结果相匹配的项的索引
  • 显示索引

  • 这是我的解决方案中的两行内容:

    N.B.我利用了我的特殊item的形状,它是带有id Prop 的obj。但这很容易概括。 sectionsitems是obj的数组。
     const Item = ({ item, itemsList }) => {
    const foundItem = itemsList.find(i => i === item.id); // find the match
    const itemIndex = itemsList.indexOf(foundItem); // get its index
    
    return (
        <View>
            <Text>{itemIndex + 1}</Text>
        </View>
    );
    };
    
    const Section = ({ section }) => (
     <View>
         <Text>{section.name}</Text>
     </View>
     );
    
     class List extends Component {
      renderList() {
        // create the `data` prop required for `SectionList` which contains `items`
        const dataSource = sections.map(s => {
            const { items, name } = s;
            return Object.assign({}, { name, key: s.id, data: items });
        });
    
        // create an array with all items' ids
        const itemsList = _.chain(sections)
            .map(s => s.items.map(item => item.id))
            .flatten()
            .value();
    
        return (
            <SectionList
                renderItem={({ item }) => (
                    <Item item={item} itemsList={itemsList} />
                )}
                renderSectionHeader={({ section }) => (
                    <Section section={section} />
                )}
                sections={dataSource} // must provide a nested array of obj with a `data` prop
                keyExtractor={item => item.id} // key for the nested array (items)
            />
        );
    }
    
    render() {
        return <View>{this.renderList()}</View>;
    }
    }
    

    07-28 02:30
    查看更多