Слайдер страницы не работает на Android, отлично работает в iOS

#javascript #react-native #react-native-android #react-native-ios

#javascript #react-native #react-native-ios

Вопрос:

Приведенный ниже код показывает, как реализованы все функции

На iOS все работает нормально, кнопка меняет слайд, точки внизу меняют состояние в зависимости от страницы, а на последней странице отображается кнопка регистрации,

На Android кнопка работает только на первой странице, на последней странице не отображается кнопка регистрации, а следующая кнопка не работает на второй странице!

 export default function introScreen({ navigation }) {
const [sliderState, setSliderState] = useState({ currentPage: 0 });
const scrollRef = useRef();
const { width, height } = Dimensions.get('window')
const notchSize = StatusBar.currentHeight

const setSliderPage = (event: any) => {
  const { currentPage } = sliderState;
  const { x } = event.nativeEvent.contentOffset;
  const indexOfNextScreen = Math.floor(x / width);
  if (indexOfNextScreen !== currentPage) {
    setSliderState({
      ...sliderState,
      currentPage: indexOfNextScreen,
    });
  }
};
const { currentPage: pageIndex } = sliderState;

const onPressTouch = () => {
  scrollRef.current?.scrollTo({
      x: width*(pageIndex 1),
      animated: true,
  });

}


return (
  <>
    <StatusBar hidden />
    <SafeAreaView style={{ flex: 1, backgroundColor:'black' }}>
      <ScrollView
        style={{ flex: 1 }}
        horizontal={true}
        scrollEventThrottle={16}
        pagingEnabled={true}
        showsHorizontalScrollIndicator={false}
        onScroll={(event: any) => {
          setSliderPage(event);
        }}
        ref={scrollRef}
      >
            <View style={{ width, height, alignItems: 'center', }}>
                <Image source={require('../../assets/images/Intorduction/1.png')} style={styles.imageStyle}  />
                <BlurView tint={'dark'} intensity={70} style={{width:'80%',borderRadius:10, marginTop:10}}>
                  <Text style={[styles.textStyle,{color:'rgb(255, 190, 46)'}]}bla bla</Text>
                </BlurView>
            </View>

            <View style={{ width, height, alignItems: 'center' }}>
                <Image source={require('../../assets/images/Intorduction/2.png')} style={styles.imageStyle} />
                <BlurView tint={'dark'} intensity={70} style={{width:'80%',borderRadius:10, marginTop:10}}>
                  <Text style={[styles.textStyle,{color:'rgb(255, 190, 46)'}]}>bla bla</Text>
                </BlurView>
            </View>

            <View style={{ width, height, alignItems: 'center' }}>
                <Image source={require('../../assets/images/Intorduction/3.png')} style={styles.imageStyle} />
                <BlurView tint={'light'} intensity={70} style={{width:'80%',borderRadius:10, marginTop:10}}>
                  <Text style={[styles.textStyle,{color:'rgb(241, 250, 238)'}]}>bla bla</Text>
                </BlurView>
            </View>
      </ScrollView>

        {pageIndex != 2 ? 
        <View style={styles.paginationWrapper}>
          {Array.from(Array(3).keys()).map((key, index) => (
            <View style={[styles.paginationDots, { opacity: pageIndex === index ? 1 : 0.2 }]} key={index} />
          ))}
        </View>
        :
        <></>
        }
        {pageIndex != 2 ? 
        <BlurView tint={'dark'} intensity={70} style={styles.nextButton}>
          <TouchableOpacity style={{flex:1, justifyContent:'center', alignItems:'center'}} onPress={onPressTouch} >
              <Text style={{color:'rgb(241, 250, 238)',fontFamily: 'poiret-one', fontSize:25}}>
                Next
              </Text>
          </TouchableOpacity>
        </BlurView>
        :
        <BlurView tint={'light'} intensity={70} style={styles.signUpButton}>
          <TouchableOpacity style={{flex:1, justifyContent:'center', alignItems:'center'}} onPress={() =>navigation.navigate('Login')} >
            <Text style={{color:'black',fontFamily: 'poiret-one', fontSize:25}}>
              Sign Up
            </Text>
          </TouchableOpacity>
        </BlurView>
        }
    </SafeAreaView>
  </>
);
}
  

Комментарии:

1. Проблема возникает из SafeAreaView. Если вы удалите его, он работает!

Ответ №1:

Я сузил проблему до ширины и «event.nativeEvent.contentOffset», возвращаемое число близко к 1, но оно равно (0.9), поэтому math.floor давал 0 в качестве индексного номера,

Я изменил Math.floor на Math.round, и он работает отлично,

Если кому-то нужен вводный слайдер для своего приложения, они могут использовать это