如果你需要实现多个呼吸灯,每个灯在一段时间后开始闪烁,以产生一种链式的动画效果,你可以在每个灯的动画开始之前加入一定的延迟。以下是如何实现这个效果的示例:
import React from 'react';
import { Animated, View, Easing } from 'react-native';
class BreathLight extends React.Component {
constructor(props) {
super(props);
this.fadeAnim = new Animated.Value(0);
this.scaleAnim = new Animated.Value(1);
}
componentDidMount() {
// 添加延迟
const { delay } = this.props;
this.timeout = setTimeout(this.startAnimation, delay);
}
componentWillUnmount() {
clearTimeout(this.timeout);
}
startAnimation = () => {
this.fadeAnim.setValue(0);
this.scaleAnim.setValue(1);
Animated.loop(
Animated.sequence([
Animated.parallel([
Animated.timing(this.fadeAnim, {
toValue: 1,
duration: 1000,
useNativeDriver: true,
easing: Easing.inOut(Easing.sin),
}),
Animated.timing(this.scaleAnim, {
toValue: 1.5,
duration: 1000,
useNativeDriver: true,
easing: Easing.inOut(Easing.sin),
}),
]),
Animated.parallel([
Animated.timing(this.fadeAnim, {
toValue: 0,
duration: 1000,
useNativeDriver: true,
easing: Easing.inOut(Easing.sin),
}),
Animated.timing(this.scaleAnim, {
toValue: 1,
duration: 1000,
useNativeDriver: true,
easing: Easing.inOut(Easing.sin),
}),
]),
]),
).start();
}
render() {
return (
<Animated.View
style={{
width: 100,
height: 100,
borderRadius: 50,
backgroundColor: 'blue',
opacity: this.fadeAnim,
transform: [{ scale: this.scaleAnim }],
}}
/>
);
}
}
export default BreathLight;
然后在父组件中,你可以像这样使用BreathLight组件:
import React from 'react';
import { View } from 'react-native';
import BreathLight from './BreathLight';
const App = () => {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<BreathLight delay={0} />
<BreathLight delay={1000} />
<BreathLight delay={2000} />
</View>
);
}
export default App;
在这个例子中,每个BreathLight的动画开始时间会有1000毫秒的间隔。你可以调整delay属性的值来改变这个间隔。