【问题标题】:Get Flatlist ItemSeparatorComponent trailing item?获取 Flatlist ItemSeparatorComponent 尾随项目?
【发布时间】:2020-03-27 15:28:03
【问题描述】:

Flatlist 允许您定义一个ItemSeparatorComponent,它接收作为默认道具highlightedleadingItem。前导 Item 表示在 分隔符之前显示的项目。

问题是我在我的平面列表中使用inverted,我的分隔符现在需要适应下一个项目而不是前一个。

有什么方法可以访问分隔符之后显示的项目?类似于 trailingItem 的东西?

【问题讨论】:

    标签: react-native react-native-flatlist


    【解决方案1】:

    如果您想拥有尾随项,可以使用separators.updateProps 添加自定义属性。下面我使用了FlatList docs 中的示例并稍作修改。在此示例中,我们突出显示了单击项目的尾随分隔符,并将 trailingItem 添加到 ItemSeparatorComponent 的 props 中。

    #输出:

    #代码:

    JSX:

    <View style={styles.container}>
      <FlatList
        ItemSeparatorComponent={(props) => {
          console.log('props', props); // here you can access the trailingItem with props.trailingItem
          return (<View style={{height: 5, backgroundColor: props.highlighted ? 'green' : 'gray'}} />);
        }}
        data={data}
        inverted
        renderItem={({item, index, separators}) => renderItem(item,index,separators)}
      />
    </View>
    

    渲染项目:

    const renderItem = (item, index, separators) => {
       return (
         <TouchableHighlight
           key={item.key}
           onPress={() => console.log('onPress')}
           onShowUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: true})}
           onHideUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: false})}>
           <View style={{backgroundColor: 'white', height: 50, justifyContent: 'center', alignItems: 'center'}}>
             <Text>{item.id}</Text>
           </View>
         </TouchableHighlight>
      );
    }
    

    #说明:

    整个魔法发生在这里:

    onShowUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: true})}
    

    从我们可以看到的文档中,updateProps 需要以下两个参数:

    选择(枚举('前导','尾随'))

    newProps(对象)

    首先我们选择trailing,然后我们可以添加我们的自定义属性。我们正在添加 trailingItem 道具,我们正在覆盖 highlighted 道具。现在我们可以使用 props.trailingItem 访问 ItemSeparatorComponent 中的道具(见上文,我在特定行留下了评论)。

    #工作示例:

    https://snack.expo.io/@tim1717/flatlist-separators

    【讨论】:

    • 这只会在 TouchableHighlight 被按下时设置 trailingItem,不是吗?我希望能够在用户输入任何内容之前访问它。
    • @RyanPergent 在这个例子中是的,但是如果你认为你可以在任何你想要的地方使用separator.updateProps(即使没有用户交互)
    • 我唯一能想到的就是在每次挂载项目时调用 updateProps。这就是它的本意吗?不贵吗?
    • @RyanPergent 你可以试试,如果太贵你会注意到的。另一个想法是评估当前滚动位置,并在此基础上设置 traillingItem?我不知道您的确切用例,但也许这会有所帮助;)
    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多