简体   繁体   English

切换 React-Native 动画值

[英]Toggle React-Native animation value

I try to toggle React-Native animation value, but my Animated.View is not animated, my translationX is "brute", without transition.我尝试切换 React-Native 动画值,但我的 Animated.View 没有动画,我的 translationX 是“brute”,没有过渡。

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();

  ...

Anyone can help me ?任何人都可以帮助我吗?

I think you try to animated your animatedValue up to its original value.我认为您尝试将您的动画值设置为原始值。

You probably need to put : const animatedValue = new Animated.Value(visible ? 0 : WINDOW_WIDTH);你可能需要把: const animatedValue = new Animated.Value(visible ? 0 : WINDOW_WIDTH);
in componentDidMount() or in constructor() and store this value on your state.componentDidMount()constructor()并将此值存储在您的状态中。

Define WINDOW_WIDTH on top.在顶部定义 WINDOW_WIDTH。

Add a listener to keep track of animated value inside the constructor.添加一个监听器来跟踪构造函数中的动画值。

Sample code示例代码

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();
  }

  ....

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

Or use a state variable to handle toggling.或者使用状态变量来处理切换。

Sample code示例代码

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 });
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM