1

目前,我的 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'

}
});

4

1 回答 1

4

如果你想在接收道具时再次动画,你应该在里面再次调用它componentWillReceiveProps()

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

componentWillReceiveProps(next) {
    if (next.props.changed) {
        this.playAnimation();
    }
}
于 2017-08-08T09:55:18.430 回答