React-Native 在动画中添加淡入淡出

Dil*_*gat 12 animation opacity react-native react-animated react-hooks

我试图让这张卡在每次组件加载时淡入,并在使用钩子卸载后淡出,但我没能做到这一点,迫切需要有人的帮助。请你告诉我如何在每次加载和卸载这张卡时使用动画hooks

这是我的组件:

import React, { useState } from "react";

const Home = (props) => {
  const renderCard = ({ item }) => {
    return (
      //I am trying to add a fadein to this everytime it loads and fadout when It unmounts
      <View>
        <Text style={styles.day}>{item}</Text>
        <MealCards
          item={state[item]}
          navigation={navigation}
          onChange={onChange}
        />
        <View style={styles.divider} />
      </View>
    );
  };
  return (
    <FlatList
      data={days}
      keyExtractor={(item) => item}
      showsHorizontalScrollIndicator={false}
      renderItem={renderCard}
    />
  );
};
Run Code Online (Sandbox Code Playgroud)

mik*_*oup 20

我认为最好的方法是使用 Reanimated。

import Animated, { FadeIn, FadeOut } from    'react-native-reanimated';

<Animated.View
            key={'uniqueKey'}
            entering={FadeIn.duration(400)}
            exiting={FadeOut.duration(400)}
        />
Run Code Online (Sandbox Code Playgroud)

额外提示:如果您想重新触发动画,您只需更改组件关键道具即可;)


小智 11

将您的组件包裹在 an 中Animated.View,并使用不透明度为其提供动画淡入淡出: https: //reactnative.dev/docs/animated

就像是

  const [fadeAnim] = useState(new Animated.Value(0));

  React.useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 1000,
    }).start();
  }, []);

  return (
    <Animated.View
      style={{
        opacity: fadeAnim,
      }}
    >
      {props.children}
    </Animated.View>
  );
Run Code Online (Sandbox Code Playgroud)

上面的代码用于淡入。淡出将在 useEffect 的返回函数中完成。


Jas*_*ers 5

基于@Benjamin Godlove 的答案,这是一个完全有效的淡入/淡出示例。

我发现由于 useEffect return 语句而尝试淡出是行不通的(我相信组件在动画有时间运行之前卸载并取消渲染),因此我保持组件已安装并仅通过切换来影响不透明度/可见性。

type Props = {
  children: React.ReactNode;
  visible: boolean;
};

function FadePanel({children, visible}:Props){
  const fadeAnim = useRef(new Animated.Value(0)).current;
  React.useEffect(() => {
    if (visible) {
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 1000,
        useNativeDriver: true,
      }).start();
    } else if (!visible) {
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 1000,
        useNativeDriver: true,
      }).start();
    }
  }, [visible]);
  return (
    <Animated.View
      style={{
        opacity:fadeAnim
      }}
    >
      {children}
    </Animated.View>
  )
}

Run Code Online (Sandbox Code Playgroud)