【问题标题】:React-native SectionList Item index to continue between sectionsReact-native SectionList 项目索引以在部分之间继续
【发布时间】:2018-06-24 15:01:35
【问题描述】:

遵循 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 从零开始。有没有其他方法可以让索引从第一部分的第一项进展到最后一部分的最后一项。有什么想法吗?

【问题讨论】:

    标签: javascript android ios reactjs react-native


    【解决方案1】:

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

    我设法让索引从第一节流到最后一节,并使用快速的香草 JS 解决方法逐项:

    1. 创建一个包含所有项目的数组
    2. 获取与array.find() 的结果匹配的项的索引
    3. 显示索引

    以下是我的解决方案中的几行:

    注意我正在利用我特定的item 形状,它是一个带有id 道具的obj。但这很容易概括。 sections 和 items 是 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>;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 2017-09-13
      • 2021-08-13
      • 1970-01-01
      • 2019-10-17
      • 2019-05-16
      • 2017-11-12
      • 1970-01-01
      • 2020-06-25
      相关资源
      最近更新 更多