Cri*_*ora 3 javascript listview scrollview reactjs react-native
语境:
我正在使用“expo”处理“react-native”,并且我有一个倒置的“FlatList”,它渲染了从一月到十二月的几个月的“数组”。
要求:
在列表显示给用户之前,列表应该集中在当月。
现在的情况:
我正在使用“FlatList”“scrollToOffset”属性来执行此请求,当接收到“数据源”列表时,会自动触发“this.flatList.scrollToOffset”语句,列表动画滚动并聚焦特定项目。但是我有一个问题,这个动画是一个破坏用户体验的突然动作。
需要:
你能帮我找到这个问题的解决方案吗?我需要做同样的事情,但用户看不到滚动运动,他只应该看到聚焦的项目。任何的想法?
演示代码:
平单
<FlatList
ref={ref => (this.flatList = ref)}
inverted
data={foods}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
Run Code Online (Sandbox Code Playgroud)
聚焦项目的功能
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,
});
}
Run Code Online (Sandbox Code Playgroud)
语句 where 是调用 handlePosition 函数
componentDidMount() {
this.handlePosition(this.props.months[2].id);
}
Run Code Online (Sandbox Code Playgroud)
使用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});
}
Run Code Online (Sandbox Code Playgroud)
对 initialScrollIndex 工作成功的必要声明
getItemLayout(data, index) {
return (
{
length: yourItemHeightSize,
offset: yourItemHeightSize * index,
index
}
);
}
Run Code Online (Sandbox Code Playgroud)
这是添加新道具的 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}
/>
Run Code Online (Sandbox Code Playgroud)