【问题标题】:New animation after setState - React NativesetState 之后的新动画 - React Native
【发布时间】:2017-08-05 16:17:06
【问题描述】:

我没有为我的 react native 应用找到问题的答案。

如果您知道如何实现这一点,那就太好了:)

我想做的事:

在页面中,当我按下某处时,我想在按下位置显示动画(例如方形幻影)。

我所取得的成就: 当我单击时,会在正确的位置显示一个带有动画的正方形。 但是当我点击其他地方时,方块的位置会改变,但动画不会重新启动。

我尝试过的:

为了制作动画,我在按下位置放置了一个 (位置:'absolute')。

这个 嵌入在一个组件中,我在我的 App 渲染中调用了 1 次:

<ClickAnimation x={item.x} y={item.y}/>

item.x 和 item.y 是坐标。

这是我的组件的代码:

import React from 'react';
import {Animated, View} from 'react-native';

export default class ClickAnimation extends React.Component {
  state = {
    scaleAnim: new Animated.Value(0)
  };
  componentWillMount() {
    Animated
      .timing(this.state.scaleAnim, {
      toValue: 2,
      duration: 500
    })
      .start();
  }
  componentWillUpdate(nextProps) {
    if (nextProps.x != this.props.x && nextProps.y != this.props.y) {
      this.setState({
        scaleAnim: new Animated.Value(0)
      })
    }
  }
  componentDidUpdate() {
    console.log("componentDidUpdate",this.state.scaleAnim)
    Animated
      .timing(this.state.scaleAnim, {
      toValue: 2,
      duration: 500
    })
      .start();
  }
  render() {
    return (<Animated.View
      style={{
      position: "absolute",
      top: this.props.y,
      left: this.props.x,
      width: 50,
      height: 50,
      backgroundColor: "red",
      transform: [
        {
          scaleY: this.state.scaleAnim
        }, {
          scaleX: this.state.scaleAnim
        }, {
          translateX: -25
        }, {
          translateY: -25
        }
      ]
    }}/>);
  }
}

componentDidUpdate 中的 console.log 给我每次点击 2 条日志:

{_children: Array(2), _value: 2, ..., _animation: null…}

{_children: Array(2), _value: 0,..., _animation: null...}

我真的不知道接下来要做什么。

PS:在 NativeScript 中,这更容易。我只需要将新组件添加到 DOM。

【问题讨论】:

    标签: react-native react-animated


    【解决方案1】:

    根据 React 文档,您不能在 componentWillUpdate() 中使用 this.setState(),如果您需要更新状态以响应 prop 更改,请改用 componentWillReceiveProps(nextProps)。

    https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

    阅读上面的链接以获取更多详细信息并检查其警告。 我希望这是导致问题的原因

    【讨论】:

    • 我尝试过使用 componentWillReceiveProps 但这并没有改变结果。 componentWillReceiveProps 中的 console.log 显示状态正确获取数据。
    • 尝试将持续时间从 500 毫秒增加到 5000 毫秒并检查发生了什么
    • Endeed,这行得通。第二次点击动画正在显示。但是动画效果不是很好。没有过渡。不知道是EXPO的问题还是de code的问题。
    【解决方案2】:

    EXPO XDE 似乎让应用程序太慢了,这就是动画部分无法正常工作的原因。

    【讨论】:

      【解决方案3】:

      我找到了解决办法。

      这伴随着这个问题:

      https://github.com/facebook/react-native/issues/6278

      我已经看到了,这就是我写第一个 0,001 的原因。但是0,001仍然很少。使用 0,01 效果很好。

      所以答案是:

      将 0 替换为 0.01,因为它太少了。

      【讨论】:

        猜你喜欢
        • 2021-05-18
        • 2018-01-20
        • 1970-01-01
        • 2019-09-26
        • 1970-01-01
        • 1970-01-01
        • 2017-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多