【问题标题】:React Native: Animation on unmountReact Native:卸载动画
【发布时间】:2020-11-24 17:55:54
【问题描述】:

我有一个类似组件的组件,它接受一个 prop 并基于这个 prop 进行渲染。每次这个道具发生变化并且组件重新渲染时,我希望新组件从 20dp 上升,旧组件下降到 20dp 并消失。我实现了第一个(缓入),但我不知道如何实现第二个(缓出)。我认为我必须在 useEffect(unmount) 的返回方法上执行此操作,但 Animated 似乎在Mount 上不起作用。

function Component({status}: Props) {
if (status === 'x') return <AnimatedView status={status}><View> xxx <View /><AnimatedView />

<AnimatedView status={status}><View> yyy <View /><AnimatedView />
}
function AnimatedView ({status}: AnimatedProps) {
  const animated = useRef(new Animated.Value(status === 'x' ? 1 : 0))
    .current;

  useEffect(() => {
    const animation = Animated.timing(animated, {
      toValue: status === 'x' ? 1 : 0,
      duration: 200,
      useNativeDriver: true
    });
    animation.start();
    return () => {
      animation.stop();
    };
  }, [animated, status]);
}
 const styles = {
    transform: [
      {
        translateY: animated.interpolate({
          inputRange: [0, 1],
          outputRange: status === 'x' ? [20, 0] : [0, 20]
        })
      }
    ],
    opacity: animatedFormHeader.interpolate({
      inputRange: [0, 1],
      outputRange:  status === 'x' ? [0, 1] : [1, 0]
    })
  };

有什么方法可以通过“react-native”动画实现这一点?我应该使用其他 API 吗?我可以举一些例子吗?实际上,我认为我应该重新编写整个内容,因为我认为动画基于道具发生并不是一个好主意。我只想在安装和卸载时为这个组件设置动画。

【问题讨论】:

    标签: reactjs animation native react-animated


    【解决方案1】:

    我根据上面的理解创建了一个组件,希望这是您想要的方式...

    小吃:https://snack.expo.io/yjEX_u_Tu

    
    export default ({ status }) => {
      const [text, setText] = useState('');
      const value = useRef(new Animated.Value(0)).current;
    
      useEffect(() => {
        const animation = Animated.timing(value, {
          toValue: 1,
          duration: 500,
        });
        animation.start(({ finished }) => {
          if (finished) {
            console.log(finished);
            setText(status ? 'Hi' : 'Bye');
            Animated.timing(value, {
              toValue: 0,
              duration: 500,
            }).start();
          }
        });
      }, [status]);
    
      const translateY = value.interpolate({
        inputRange: [0, 1],
        outputRange: [0, 20],
      });
    
      const opacity = value.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 0.2],
      });
      return (
        <Animated.View
          style={[styles.container, { opacity, transform: [{ translateY }] }]}>
          <Animated.Text style={{ color: 'white' }}>{text}</Animated.Text>
        </Animated.View>
      );
    };
    

    【讨论】:

    • 这是一个非常好的方法,但这里的问题是你有一个你在 useEffect 中改变的状态但在我有“孩子”并且“缓出”动画发生在安装而不是卸载。
    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 2017-10-12
    • 2021-01-30
    • 2023-03-16
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多