切换React-Native动画值

时间:2019-07-02 14:40:36

标签: react-native animation

我尝试切换React-Native动画值,但是我的Animated.View没有动画,我的translationX是“粗略的”,没有过渡。

const OffCanvas = ({ visible, close }) => {
  const WINDOW_WIDTH = Dimensions.get('window').width;
  const animatedValue = new Animated.Value(visible ? 0 : WINDOW_WIDTH);

  Animated.timing(animatedValue, {
    toValue: visible ? 0 : WINDOW_WIDTH,
    duration: 250,
    easing: Easing.elastic(0.7),
    delay: 0
  }).start();

  ...

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我认为您尝试将自己的animationValue设置为原始值。

您可能需要输入: const animatedValue = new Animated.Value(visible ? 0 : WINDOW_WIDTH);
componentDidMount()constructor()中,并将此值存储在您的状态。

答案 1 :(得分:0)

在顶部定义WINDOW_WIDTH。

添加一个侦听器,以跟踪构造函数内部的动画值。

示例代码

const WINDOW_WIDTH = Dimensions.get('window').width;

export default class Calls extends Component {
  constructor() {
    super();
    this.animatedValue = new Animated.Value(0);
    this.animatedValue.addListener(({ value }) => this._value = value);
  }

  toggle=() => {
    const offset = JSON.parse(JSON.stringify(this.animatedValue));
    Animated.timing(this.animatedValue, {
      toValue: offset > WINDOW_WIDTH ? 0 : WINDOW_WIDTH,
      duration: 250,
      easing: Easing.elastic(0.7),
    }).start();
  }

  ....

================================================ ====

或者使用状态变量来处理切换。

示例代码

const WINDOW_WIDTH = Dimensions.get('window').width;
export default class Calls extends Component {
 state = { toggle: false };

  toggle=() => {
    const { toggle } = this.state;
    Animated.timing(this.animatedValue, {
      toValue: toggle ? 0 : WINDOW_WIDTH,
      duration: 250,
      easing: Easing.elastic(0.7),
    }).start(() => {
      this.setState({ toggle: !toggle });
    });
  }