0

目前,我的React Native动画只发生一次,而不再发生。每当我的某个组件的道具发生变化时,我都需要它。当新的道具数据进入时,我的数据显示会发生变化,但它只是第一次动画。每当道具改变/组件更新时,我有没有办法让动画再次发生?如何使React原生动画再次发生?

这是我到目前为止有:

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' 
 

 
} 
 
});

回答

1

如果你想获得的道具,当再次动画,你应该再次调用里面componentWillReceiveProps()

playAnimation() { 
    Animated.timing(
     this.state.yAnimation, 
     { 
      toValue: 0, 
      duration: 150, 
     } 
    ).start(); 
} 

componentWillReceiveProps(next) { 
    if (next.props.changed) { 
     this.playAnimation(); 
    } 
}