首页 > 解决方案 > 反应原生动画不透明度和位置

问题描述

我想在我的应用程序中创建一个动画,其中包括转换视图的位置和不透明度。现在,我所拥有的只是转换视图,我已经这样做了:

const fadeAnim = useRef(new Animated.Value(0)).current
useEffect(()=> {
  Animated.timing(
    fadeAnim,
    {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true,
      delay: 2000,
    }
  ).start();
}, [fadeAnim])

<Animated.View style={{
     opacity: fadeAnim
  }}>
{content}
</Animated.View>

我怎样才能编辑它来转换位置,然后几秒钟后,我想隐藏这个容器。

标签: react-native

解决方案


我建议对动画有一个更通用的功能,这样你就可以把它放在一个单独的文件中,并在你需要的任何地方使用它。像这样的东西:

 const opacityRef = useRef(new Animated.Value(0)).current
 const translateRef = useRef(new Animated.Value(0)).current

 const initialX = 0
 const finalX = 100 // these values should be put inside constants so you'll have to change them if you need to only in one place
 
 
  // this is a general animation function, you can use it for opacity, translations, rotations
  const animateView = (toValue: number, animatedRef: Animated.Value, duration: number, delay: number) => {
    return Animated.timing(
      animatedRef,
      {
        toValue,
        duration,
        useNativeDriver: true,
        delay,
      }
    )
  } 


  // you can implement sequences of animations or even parallel if you need to (take a look at the docs)
   useEffect(()=> {
    Animated.sequence([
      animateView(finalX, translateRef, 1000, 0),
      animateView(initialX, translateRef, 1000, 0),
      animateView(0, opacityRef, 1000, 2000),
      animateView(1, opacityRef, 1000, 0),

    ]).start()

  }, [])
  
  
   return (
    <Animated.View style={{
      backgroundColor: 'red',
      width: 100,
      height: 100,
      left: 0,
      opacity: opacityRef,
      transform: [{
        translateX: translateRef
      }]

    }}/>
  )


推荐阅读