首页 > 解决方案 > 使用useRef在平面列表中单独动画项目 - 反应原生?

问题描述

当按下 In/Out 时,我正在尝试动画“缩放”项目,

但是当按下列表中的任何项目时出现问题,随机项目被缩放!

我在按下时将每个项目的活动索引设置为 Ref 并设置一个条件来根据它缩放项目但效果不佳:\

这是我的代码片段

直播)一个在这里。

import React from 'react';
import {
  FlatList,
  SafeAreaView,
  Text,
  Pressable,
  Animated,
} from 'react-native';

const examples = [
  {
    key: 1,
    name: 'Animated Progress Bar Indicator',
  },
  {
    key: 2,
    name: 'FlatList Carousel Animation 1',
  },
  {
    key: 3,
    name: 'FlatList Carousel Animation 2',
  },
  {
    key: 4,
    name: 'FlatList Carousel Animation 3',
  },
];

const HomeScreen = ({navigation}) => {
  const scaleItem = React.useRef(new Animated.Value(1)).current;
  const activeIndexRef = React.useRef(null);

  const onPressInItem = (inds) => {
    activeIndexRef.current = inds;
    console.log('activeIndexRef', activeIndexRef.current);
    Animated.spring(scaleItem, {
      toValue: 0.95,
      useNativeDriver: true,
    }).start();
    console.log(inds === activeIndexRef.current ? 'hey' : 'no');
  };

  const onPressOutItem = (inds) => {
    activeIndexRef.current = inds;
    console.log('activeIndexRef-onPressOutItem', activeIndexRef.current);
    Animated.spring(scaleItem, {
      toValue: 1.0,
      useNativeDriver: true,
    }).start();
    console.log(inds === activeIndexRef.current ? 'hey' : 'no');
  };

  return (
    <SafeAreaView style={styles.container}>
    
      <FlatList
        data={examples}
        keyExtractor={(item) => item.key.toString()}
        renderItem={({item, index}) => {
          return (
            <Pressable
              onPressIn={() => onPressInItem(index)}
              onPressOut={() => onPressOutItem(index)}>
              <Animated.View
                style={{
                  flexDirection: 'row',
                  backgroundColor: '#56f',
                  alignItems: 'center',
                  paddingVertical: 10,
                  marginVertical: 10,
                  transform: [
                    {
                      scale: activeIndexRef.current === index ? scaleItem : 1,
                    },
                  ],
                }}>
                <Text style={styles.itemTitle}> </Text>
                <Text style={styles.itemTitle}>{item.name}</Text>
              </Animated.View>
            </Pressable>
          );
        }}
      />
    </SafeAreaView>
  );
};

export default HomeScreen;

标签: javascriptreactjsreact-native

解决方案


推荐阅读