Есть ли способ сделать Animated.Value массивом в React Native?

Я хочу хранить высоты нескольких <View>s в массиве, и анимировать все эти значения вместе. Что-то вроде этого:

<Animated.View style={{height: this.state.heights[0]}}/>
<Animated.View style={{height: this.state.heights[1]}}/>
<Animated.View style={{height: this.state.heights[2]}}/>

Однако, когда я пытаюсь сделать это:

this.state = {
  heights: new Animated.Value([10, 20, 30])
}

это не работает

Какие-нибудь советы?

2 ответа

Создать массив Animated.Value лайк

this.heights = [new Animated.Value(10), new Animated.Value(20), new Animated.Value(30)];

Затем используйте функцию создания анимации для запуска анимации в соответствии с вашими требованиями

Animated.parallel([
  Animated.timing(this.heights[0], { toValue: **, duration: **}),
  Animated.timing(this.heights[1], { toValue: **, duration: **}),
  Animated.timing(this.heights[2], { toValue: **, duration: **})
]).start()

Затем используйте this.heights в методе рендерера, как

<Animated.View style={{height: this.heights[0]}}/>
<Animated.View style={{height: this.heights[1]}}/>
<Animated.View style={{height: this.heights[2]}}/>

Надеюсь, это поможет!

Спасибо вам за публикацию. Итак, я следую этому примеру в своем коде, но по какой-то причине моя анимация не запускается. Массив из useRef изменяется, но анимация не работает, есть идеи, в чем может быть проблема, вот мой код. Я пытаюсь расширить свою карточку, чтобы увеличить высоту всякий раз, когда пользователь нажимает кнопку «Просмотр информации». Спасибо!

        const animateCardAll = useRef([]);


{markersArr.map((marker, index) => {
          animateCardAll.current[index] = new Animated.Value(CARD_HEIGHT);
          marker.isExpanded = false;
          (marker.imageFetched = false), console.log(marker);
          return (
            <>
              <Animated.View
                key={marker._id}
                style={[
                  styles.card,
                  {
                    height: animateCardAll.current[index],
                  },
                ]}
              >
                {marker.imageId ? (
                  <LazyImage
                    index={index}
                    //visibleImages={visibleImages}
                    imageId={marker.imageId}
                    userToken={userToken}
                    ref={(cardRefs.current[index] = marker)}
                  />
                ) : null}
                <View style={styles.textContent}>
                  <Text style={styles.cardTitle} numberOfLines={1}>
                    Address: {marker.address}
                  </Text>
                  
                  <Text style={styles.cardDescription} numberOfLines={1}>
                    {marker.city}, {marker.zip_code} {marker.uSstate}
                  </Text>
                  
                  {cardRefs.current[index] &&
                  cardRefs.current[index].isExpanded ? (
                    <ReviewsComponent
                      index={index}
                      addressId={marker._id}
                      userToken={userToken}
                    />
                  ) : null}
                </View>

                <View style={styles.button}>
                  <TouchableOpacity
                    onPress={() => {
                      expandCardAll(index);
                    }}
                    style={[
                      styles.signIn,
                      {
                        borderColor: "#398984",
                        borderWidth: 1,
                      },
                    ]}
                  >
                    <Text
                      style={[
                        styles.textSign,
                        {
                          color: "#398984",
                        },
                      ]}
                    >
                      VIEW INFORMATION
                    </Text>
                  </TouchableOpacity>
                </View>
              </Animated.View>
            </>
          );
        })}
      </Animated.ScrollView>
    ) : null}

 const expandCardAll = (index) => {


cardRefs.current[index].isExpanded = !cardRefs.current[index].isExpanded; // Toggle the expanded state

const upadtedHeight = cardRefs.current[index].isExpanded
  ? SCREEN_HEIGHT * 0.65
  : CARD_HEIGHT;
console.log(
  "Expanded",
  cardRefs.current[index],
  animateCardAll.current[index],
  animateCardAll,
  upadtedHeight
);

Animated.timing(animateCardAll.current[index], {
  toValue: upadtedHeight,
  duration: 500,
  useNativeDriver: false,
}).start(); };

Как я уже упоминал, значение в моем animateCardAll.current[index] обновляется правильно, но анимация не запускается.

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