目前,我的React Native动画只发生一次,然后再也不会发生。每当我为该组件改变一个道具时,我都需要它。当新的道具数据进入时,我的数据显示会发生变化,但它只是第一次动画。有没有办法让每次道具更改/组件更新时动画再次发生?
这是我到目前为止所做的:
import React from 'react';
import {Animated, Easing, StyleSheet, Text, View} from 'react-native';
//Animation
class FadeInView extends React.Component {
state = {
yAnimation: new Animated.Value(21),
}
componentDidMount() {
Animated.timing(
this.state.yAnimation,
{
//easing: Easing.bounce,
toValue: 0,
duration: 150,
}
).start();
}
render() {
let { yAnimation } = this.state;
return (
<Animated.View
style={{
...this.props.style,
transform: [{translateY: this.state.yAnimation}],
}}
>
{this.props.children}
</Animated.View>
);
}
}
//Price Component
export default class Price extends React.Component {
constructor(props) {
super(props);
this.animateNow = false;
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.price !== nextProps.price) {
console.log('true');
return true;
} else {
return false;
}
}
componentWillUpdate() {
if (this.props.price != this.localPrice) {
this.animateNow = true;
}
}
componentDidUpdate() {
this.localPrice = this.props.price;
this.animateNow = false;
console.log(this.props.price);
}
render() {
if (this.animateNow) {
return (
<FadeInView>
<Text style={styles.price}>{this.props.price}</Text>
</FadeInView>
);
} else {
return (
<View>
<Text style={styles.price}>{this.props.price}</Text>
</View>
);
}
}
}
const styles = StyleSheet.create({
price: {
fontFamily: 'Avenir',
fontSize: 21,
color: '#606060',
textAlign: 'right',
marginRight: 20,
backgroundColor: 'transparent'
}
});
答案 0 :(得分:3)
如果你想在收到道具时再次动画,你应该在componentWillReceiveProps()
内再次打电话:
playAnimation() {
Animated.timing(
this.state.yAnimation,
{
toValue: 0,
duration: 150,
}
).start();
}
componentWillReceiveProps(next) {
if (next.props.changed) {
this.playAnimation();
}
}