gpt4 book ai didi

javascript - FlatList react native : How i can focus scroll in the specific list item

转载 作者:行者123 更新时间:2023-11-30 09:16:39 24 4
gpt4 key购买 nike

上下文:

我正在使用“expo”处理“react-native”,我有一个倒置的“FlatList”,它呈现从一月到十二月的月份“数组”。

enter image description here

请求:

在列表显示给用户之前,列表应该聚焦在当月。

现状:

我正在使用“FlatList”“scrollToOffset”属性来执行此请求,当列表接收到“数据源”时会自动触发“this.flatList.scrollToOffset”语句,列表会为滚动设置动画并聚焦特定项目.但是我有一个问题,这个动画是一个突然的 Action ,破坏了用户体验。

enter image description here

需要:

你能帮我找到解决这个问题的方法吗?我需要做同样的事情,但用户看不到那个滚动 Action ,他应该只看到聚焦的项目。有什么想法吗?

演示代码:

平面列表

<FlatList
ref={ref => (this.flatList = ref)}
inverted
data={foods}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>

关注项目的功能

handlePosition(id) {
/* Item Size from FlatList */
const itemSize = deviceWidth / 2 + 30;
/* Id of the current month */
const idCurrentItem = id;

this.flatList.scrollToOffset({
animated: true,
offset: itemSize * idCurrentItem,
});
}

调用handlePosition函数的语句

componentDidMount() {
this.handlePosition(this.props.months[2].id);
}

最佳答案

使用 FlatList 组件的 initialScrollIndex prop 来排序您想要开始 FlatList 的索引。

为此,您必须在 componentDidMount 或 componentWillMount 函数中计算渲染之前的月份,您必须在其中存储月份(或索引)在状态中。然后,您将在 Flatlist 组件中访问此状态并为其设置 initialscrollIndex。

这里是 componentWillMount 函数的例子:

componentWillMount() {
...
//assuming that we are on February will set index scroll to 1 being 0 January
//and being 3 March
this.setState({monthToStart: 1});
}

initialScrollIndex 工作成功的必要声明

getItemLayout(data, index) {
return (
{
length: yourItemHeightSize,
offset: yourItemHeightSize * index,
index
}
);
}

这里是 FlatList 组件添加新 prop 的例子:

  <FlatList
ref={ref => (this.flatList = ref)}
inverted
data={foods}
keyExtractor={this.keyExtractor}
getItemLayout={(data, index) => this.getItemLayout(data, index)}
renderItem={this.renderItem}
initialScrollIndex={this.state.monthToStart}
/>

关于javascript - FlatList react native : How i can focus scroll in the specific list item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54662444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com