基础动画
1、设置动画属性对象
函数组件使用useRef
const viewHeight = useRef(new Animated.Value(0)).current;
2、将动画属性对象绑定到要动画的组件style上,当属性来使用
如style={{height:viewHeight}}
3、设置动画
Animated.timing(要改变的动画属性对象,{
toValue:改变动画属性的最终值
duration:持续时间毫秒数
}).start()
这一过程经过特别优化,执行效率会远高于反复调用setState和多次重渲染。
easing动画过渡方式
- easing:Easing.in(Easing.bounce) ,平滑进入,弹动结束
example 动态改变元素的height
import React, {useRef} from 'react';
import {Animated, Text, View, StyleSheet, Button, Easing} from 'react-native';
const App = () => {
const viewHeight = useRef(new Animated.Value(0)).current;
const show = () => {
Animated.timing(viewHeight, {
toValue: 300,
duration: 1000,
easing: Easing.in(Easing.bounce),
}).start();
};
const hide = () => {
Animated.timing(viewHeight, {
toValue: 0,
duration: 1000,
easing: Easing.inOut(Easing.linear),
}).start();
};
return (
<View style={styles.container}>
<Animated.View
style={{
backgroundColor: 'red',
height: viewHeight,
}}>
<Text style={styles.fadingText}>animation view</Text>
</Animated.View>
<View style={styles.buttonRow}>
<Button title="Show" onPress={show} />
<Button title="Hide" onPress={hide} />
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
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>
);