Как изменить порядок компонентов в карусели стека React Native?

Я пытаюсь встроить карусель стека в свое реагирующее приложение, используя React-Native-Reanimanted и обработчик жестов. Предполагается, что приложение отображает стопку компонентов друг над другом, и когда пользователь проводит пальцем вверх, компонент появляется и располагается поверх предыдущего компонента.

Вместо этого, когда я запускаю симулятор, когда пользователь проводит пальцем вверх, появившиеся компоненты располагаются позади предыдущего компонента, а не поверх него.

Это код компонента, который будет находиться внутри контейнера (думаю, проблема здесь):

import React from 'react';
import {SafeAreaView, View} from 'react-native-safe-area-context';
import Stack from '../Stack/Stack';
import Animated, {
  useAnimatedStyle,
  interpolate,
  withTiming,
} from 'react-native-reanimated';
import {
  FlingGestureHandler,
  Directions,
  State,
} from 'react-native-gesture-handler';
import {StyleSheet} from 'react-native';

const Card = ({
  item,
  index,
  animatedValue,
  currentIndex,
  prevIndex,
  datalength,
  maxVisibleItems,
}) => {
  const animatedStyle = useAnimatedStyle(() => {
    const translateY = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [-10, 1, 10],
    );
    const translateY2 = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [-200, 1, 200],
    );
    const scale = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [0.9, 1, 1.1],
    );
    const opacity = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [1, 1, 0],
    );

    return {
      transform: [
        {
          translateY: index === prevIndex.value ? translateY2 : translateY,
        },
        {scale},
      ],
      opacity:
        index < currentIndex.value + maxVisibleItems - 1
          ? opacity
          : index === currentIndex.value + maxVisibleItems - 1
          ? withTiming(1)
          : withTiming(0),
    };
  });

  return (
    <FlingGestureHandler
      key = "up"
      direction = {Directions.UP}
      onHandlerStateChange = {ev => {
        if (ev.nativeEvent.state === State.END) {
          if (currentIndex.value !== 0) {
            animatedValue.value = withTiming((currentIndex.value -= 1));
            prevIndex.value = currentIndex.value - 1;
          }
        }
      }}>
      <FlingGestureHandler
        key = "down"
        direction = {Directions.DOWN}
        onHandlerStateChange = {ev => {
          if (ev.nativeEvent.state === State.END) {
            if (currentIndex.value !== datalength - 1) {
              animatedValue.value = withTiming((currentIndex.value += 1));
              prevIndex.value = currentIndex.value;
            }
          }
        }}>
        <Animated.View style = {animatedStyle}>
          <Stack
            title = {item.title}
            title1 = {item.title1}
            style = {{zIndex: datalength - index}}
          />
        </Animated.View>
      </FlingGestureHandler>
    </FlingGestureHandler>
  );
};

export default Card;

const styles = StyleSheet.create({
  image: {
    position: 'absolute',
    borderRadius: 20,
  },
});

также код контейнера:

import {StyleSheet, Text, View} from 'react-native';
import React from 'react';
import Stack from '../Stack/Stack';
import {useSharedValue} from 'react-native-reanimated';
import Card from '../Card/Card';

const CardContainer = ({data, maxVisibleItems}) => {
  const animatedValue = useSharedValue(0);
  const currentIndex = useSharedValue(0);
  const prevIndex = useSharedValue(0);
  return (
    <>
      {data.map((item, index) => {
        return (
            // or Stack 
          <Card
            maxVisibleItems = {maxVisibleItems}
            key = {index}
            item = {item}
            index = {index}
            animatedValue = {animatedValue}
            currentIndex = {currentIndex}
            prevIndex = {prevIndex}
            datalength = {data.length}
          />
        );
      })}
    </>
  );
};

export default CardContainer;

Я пробовал поиграться с некоторыми значениями в TranslateY и TranslateY2, но безуспешно, как и с индексами.

Вы проверяли эту библиотеку github.com/dohooo/react-native-reanimated-carousel?

ko100v.d 25.02.2024 11:10

@ko100v.d спасибо за идею! Я просмотрел библиотеку, но мне нужно было решение, которое относится к компоненту, который я создал сам, вместо использования предустановленной библиотеки.

melbel 27.02.2024 14:20
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Массив зависимостей в React
Массив зависимостей в React
Все о массиве Dependency и его связи с useEffect.
1
2
83
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Хорошо, я понял это:

Я добавил функцию ZIndex: Это компонент карты:

import React from 'react';
import Stack from '../Stack/Stack';
import Animated, {
  useAnimatedStyle,
  interpolate,
  withTiming,
} from 'react-native-reanimated';
import {
  FlingGestureHandler,
  Directions,
  State,
} from 'react-native-gesture-handler';

const Card = ({
  item,
  index,
  animatedValue,
  currentIndex,
  prevIndex,
  datalength,
  maxVisibleItems,
}) => {
  const animatedStyle = useAnimatedStyle(() => {
    const translateY = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [-5, 1, 5],
    );
    const translateY2 = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [-200, 1, 200],
    );
    const scale = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [0.9, 1, 1.1],
    );
    const opacity = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [1, 1, 0],
    );

    const zIndex = interpolate(
      animatedValue.value,
      [index - 1, index, index + 1],
      [1, 2, 3], 
    );
//psej
    return {
      transform: [
        {
          translateY: index === prevIndex.value ? translateY2 : translateY,
        },
        {scale},
      ],
      opacity:
        index < currentIndex.value + maxVisibleItems - 1
          ? opacity
          : index === currentIndex.value + maxVisibleItems - 1
          ? withTiming(1)
          : withTiming(0),
      zIndex,
    };
  });

  return (
    <FlingGestureHandler
      key = "up"
      direction = {Directions.UP}
      onHandlerStateChange = {ev => {
        if (ev.nativeEvent.state === State.END) {
          if (currentIndex.value !== 0) {
            animatedValue.value = withTiming((currentIndex.value -= 1));
            prevIndex.value = currentIndex.value - 1;
          }
        }
      }}>
      <FlingGestureHandler
        key = "down"
        direction = {Directions.DOWN}
        onHandlerStateChange = {ev => {
          if (ev.nativeEvent.state === State.END) {
            if (currentIndex.value !== datalength - 1) {
              animatedValue.value = withTiming((currentIndex.value += 1));
              prevIndex.value = currentIndex.value;
            }
          }
        }}>
        <Animated.View style = {animatedStyle}>
          <Stack
            title = {item.title}
            title1 = {item.title1}
            style = {{zIndex: datalength - index}}
          />
        </Animated.View>
      </FlingGestureHandler>
    </FlingGestureHandler>
  );
};
export default Card;

Другие вопросы по теме

Похожие вопросы