javascript - FlatList React-Native:我如何在特定列表项中聚焦滚动
问题描述
语境:
我正在使用“expo”处理“react-native”,并且我有一个倒置的“FlatList”,它在其中呈现从 1 月到 12 月的几个月的“数组”。
要求:
在将列表显示给用户之前,列表应该集中在当前月份。
现在的情况:
我正在使用“FlatList”“scrollToOffset”属性来执行此请求,当列表接收到“数据源”时,会自动触发“this.flatList.scrollToOffset”语句,列表动画滚动并聚焦特定项目。但是我有一个问题,这个动画是一个破坏用户体验的突然运动。
需要:
你能帮我找到解决这个问题的方法吗?我需要做同样的事情,但用户看不到滚动运动,他只应该看到项目集中。任何想法?
演示代码:
平面列表
<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 属性来排序要在其中启动 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 组件添加新道具的示例:
<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 - $this 在 .each() 函数内的函数内不起作用
- excel - 如何确保 Excel 不会更改其他语言版本中数据标签的数字格式?
- c# - 会话变量导致控制器操作一次触发一个
- r - 如何使用美学为 geom_hline() 着色?
- android - 如何计算哪个视图占据了屏幕的一半以上
- sql - Postgres在一定时间内按前缀选择然后对其进行排序..性能缓慢
- material-ui - 生成的jss类名自定义?
- sql - inner join combined with a count
- c# - NLog:如果填充了字段,则记录到单个文件
- c++ - C++ std::swap 无效参数