1

我有一系列月份,我使用水平 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>
4

2 回答 2

2

尝试使用 ref 访问current它,它应该可以工作

this.flatRef.current.scrollToIndex({index: monthName.length > this.state.currentindex ? this.state.currentindex++ : this.state.currentindex });
于 2021-03-20T08:58:11.807 回答
0

FlatList我建议您不要使用 a来创建一个state变量并像这样执行它

工作示例 -这里

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>
  );
于 2021-05-03T10:32:01.787 回答