基础动画

1、设置动画属性对象
函数组件使用useRef
const viewHeight = useRef(new Animated.Value(0)).current;

2、将动画属性对象绑定到要动画的组件style上,当属性来使用
如style={{height:viewHeight}}

3、设置动画
Animated.timing(要改变的动画属性对象,{
toValue:改变动画属性的最终值
duration:持续时间毫秒数
}).start()

这一过程经过特别优化,执行效率会远高于反复调用setState和多次重渲染。

easing动画过渡方式

https://easings.net/

  • easing:Easing.in(Easing.bounce) ,平滑进入,弹动结束

example 动态改变元素的height

  1. import React, {useRef} from 'react';
  2. import {Animated, Text, View, StyleSheet, Button, Easing} from 'react-native';
  3. const App = () => {
  4. const viewHeight = useRef(new Animated.Value(0)).current;
  5. const show = () => {
  6. Animated.timing(viewHeight, {
  7. toValue: 300,
  8. duration: 1000,
  9. easing: Easing.in(Easing.bounce),
  10. }).start();
  11. };
  12. const hide = () => {
  13. Animated.timing(viewHeight, {
  14. toValue: 0,
  15. duration: 1000,
  16. easing: Easing.inOut(Easing.linear),
  17. }).start();
  18. };
  19. return (
  20. <View style={styles.container}>
  21. <Animated.View
  22. style={{
  23. backgroundColor: 'red',
  24. height: viewHeight,
  25. }}>
  26. <Text style={styles.fadingText}>animation view</Text>
  27. </Animated.View>
  28. <View style={styles.buttonRow}>
  29. <Button title="Show" onPress={show} />
  30. <Button title="Hide" onPress={hide} />
  31. </View>
  32. </View>
  33. );
  34. };
  35. const styles = StyleSheet.create({
  36. container: {
  37. flex: 1,
  38. alignItems: 'center',
  39. justifyContent: 'center',
  40. },
  41. });
  42. export default App;

https://blog.csdn.net/weixin_43294560/article/details/105112537
https://reactnative.cn/docs/animations
https://reactnative.cn/docs/animated#%E9%85%8D%E7%BD%AE%E5%8A%A8%E7%94%BB

并行动画

实现高度条的波浪

// 准备并行动画的值
const [anim, setAnim] = useState<Animated.Value[]>(
  [] as unknown as Animated.Value[],
  );

useEffect(() => {
  const list: Animated.Value[] = [];
  for (let i = 0; i < 10; i++) {
    list.push(new Animated.Value(8));
  }
  setAnim(list);
}, []);

const startAnimation = () => {
  const animatedFun = Animated.stagger(
    80,
    anim.map(val => {
      return Animated.timing(val, {
        toValue: waveHeight,
        duration: 300,
        easing: Easing.bounce,
        useNativeDriver: false,
      });
    }),
  );
  animatedFun.start();
};


// 在组件中使用
const rippleComponent = anim.map((val, index) => {
  return (
    <Animated.View
      key={'animated_view_' + index}
      style={[
        {backgroundColor: '#FFF', borderRadius: mpx(1)},
        {
          marginHorizontal: mpx(1.5),
          width: mpx(3),
          height: val, // 动画的值
        },
      ]}></Animated.View>
  );
});

return (
  <View>
    {rippleComponent}
  </View>
);

https://www.jianshu.com/p/7fd37d8ed138