如何解决如何在 React Native 中使用 FlatList 单击按钮滚动到下一项?
我有一个月份数组,用于使用水平 FlatList 显示月份。我希望使用 2 个按钮来更改月份,这些按钮是向前按钮以按递增顺序更改月份,即从一月到二月等,并使用后退按钮向后更改月份,即从一月到十二月。
我怎样才能让按钮这样做。在monthName下面是一个包含所有月份名称的数组。
<ScrollView style={{flexGrow: 1}}>
<View style={{flex: 1,backgroundColor: '#fff',height: hp('130')}}>
<View
style={{
justifyContent: 'space-evenly',width: wp('48'),}}>
<FlatList
data={monthName}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
renderItem={(month,index) => (
<View>
<Months
showMonth={month.item}
id={month.id}
refer={flatRef}
/>
</View>
)}
keyExtractor={(item,index) => item.id.toString()}
horizontal
// snapToInterval={Dimensions.get('window').width}
snapToAlignment={'center'}
ref={(node) => (flatRef = node)}
/>
</View>
<View
style={{
justifyContent: 'space-evenly',width: wp('12'),}}>
{/* {} */}
<IonIcons.Button --> the button that makes the month increment.
name="arrow-forward"
size={25}
backgroundColor="white"
color="black"
// onPress={() => console.log('pressed')}
onPress={() => {
flatRef.scrollToIndex({index: ?});
}}
/>
</View>
</View>
</ScrollView>
解决方法
尝试使用 current
访问 ref,它应该可以工作
this.flatRef.current.scrollToIndex({index: monthName.length > this.state.currentindex ? this.state.currentindex++ : this.state.currentindex });
,
我建议您创建一个 FlatList
变量并像这样执行它,而不是使用 state
工作示例 - Here
import * as React from 'react';
import { Text,View,StyleSheet } from 'react-native';
import { AntDesign } from '@expo/vector-icons';
...
const [SelectMonth,SetSelectMonth] = React.useState(monthName[0]);
const NextPress = () => {
if (SelectMonth.id !== 12) {
let temp = monthName.find((c) => c.id === SelectMonth.id + 1);
if (temp) {
SetSelectMonth(temp);
}
}
};
const PrevPress = () => {
if (SelectMonth.id !== 1) {
let temp = monthName.find((c) => c.id === SelectMonth.id - 1);
if (temp) {
SetSelectMonth(temp);
}
}
};
return (
<View style={styles.container}>
<View style={styles.CalenderBox}>
<AntDesign
name="caretleft"
size={30}
color="black"
onPress={() => PrevPress()}
/>
<View style={styles.MonthNameBox}>
<Text style={{ fontWeight: 'bold',fontSize: 24 }}>
{SelectMonth.name}
</Text>
</View>
<AntDesign
name="caretright"
size={30}
color="black"
onPress={() => NextPress()}
/>
</View>
</View>
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。