0

我想渲染 7 个容器,我想为它们的背景颜色设置动画 onPress。当我选择第一个时一切都很好,它会动画,但是当我按下第二个时,第一个容器的背景消失(组件的宽度回到 "0%" )。

小吃:https://snack.expo.dev/@georgipavlov/bold-french-fries

容器:

import { LinearGradient } from "expo-linear-gradient"
const GradientcontainerAnimated = ({ categories, category, setCategories }) => {
  const colors = category.color;
  const width = useSharedValue("0%");

  const animatedStyle = useAnimatedStyle(() => {
    return { width: width.value };
  });

  const AnimatedLinearGradient =
    Animated.createAnimatedComponent(LinearGradient);

  const handleSelect = () => {
    let data = [...categories];
    const index = data.indexOf(category);
    const toValue = !category.selected ? "100%" : "0%";
    width.value = withTiming(toValue, {
      duration: 500,
      easing: Easing.inOut(Easing.ease),
    });

    data[index].selected = !data[index].selected;
    setCategories([...data]);
  };

  return (
    <TouchableOpacity
      style={[
        styles.categoryContainer,
      ]}
      onPress={() => handleSelect()}
    >
      <AnimatedLinearGradient
        colors={colors}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={[styles.gradientContainer, animatedStyle]}
      />
      <LinearGradient style={styles.gradientCircle} colors={colors} />
      <AppText style={{ marginTop: 15 }}>{category.category}</AppText>
    </TouchableOpacity>
  );
}; 

这就是我渲染它们的方式:

export default function SelfTherapyChooseCategory() {
  const [categories, setCategories] = useState([]);

  useEffect(() => {
    let data = [];
    Object.keys(categoriesData).forEach((category, index) => {
      data.push({
        category: category,
        selected: false,
        color: categoriesData[category].color,
      });
    });
    setCategories([...data]);
  }, []);

  return (
    <Screen>
      <ScrollView>
        {categories.map((category, index) => {
          return (
            <GradientcontainerAnimated
              key={index}
              categories={categories}
              category={category}
              setCategories={setCategories}
            />
          );
        })}
      </ScrollView>
    </Screen>
  );
}
4

0 回答 0