【问题标题】:React native animation of a View from side to side从一侧到另一侧反应视图的本机动画
【发布时间】:2017-10-22 14:54:13
【问题描述】:

我最近正在处理 react-native 的动画,我正在尝试通过单击使 View 组件从一侧移动到另一侧。 这是我到目前为止有效的代码:

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Animated,
  Easing,
  TouchableOpacity,
  Dimensions
} from 'react-native';

export default class App extends Component {
  constructor () {
    super()
    this.state = {
      isLeftSide: true,
    }
    this.animatedValue = new Animated.Value(0)
  }

  animate () {
    this.animatedValue.setValue(0);
    Animated.timing(
      this.animatedValue,
      {
        toValue: 1,
        duration: 300,
        easing: Easing.linear
      }
    ).start()
  }

  fire = () => { 
    this.animate();
    this.setState({isLeftSide: (!this.state.isLeftSide)});
  }

  direction = () => this.state.isLeftSide ? 'rtl' : 'ltr';

  render() {
    const screenWidth = Dimensions.get('screen').width;
    const objectMaxCoord = screenWidth - 40;

    const outputRange = {
      rtl: [0, objectMaxCoord],
      ltr: [objectMaxCoord, 0]
    }
    const marginLeft = this.animatedValue.interpolate({
      inputRange: [0, 1],
      outputRange: outputRange[this.direction()]
    })
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={() => this.fire()}><Text>Run</Text></TouchableOpacity>
        <Animated.View
          style={{
            marginLeft,
            height: 30,
            width: 40,
            backgroundColor: 'red'}} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
    marginTop: 30
  }
});

现在,问题是红色立方体从左侧开始,但是当我单击运行时,它会(没有动画)跳到右上角,然后平滑地(在动画中)移动到左侧。之后的工作非常完美。为什么会发生第一次跳转?

有没有更简单的方法来制作这个动画?

(P.S 我正在研究安卓) 这是一个博览会的链接 https://snack.expo.io/S1aAgNq6Z

【问题讨论】:

    标签: react-native react-native-android


    【解决方案1】:

    可能是因为状态可能不会立即更新。尝试像这样更改您的开火功能:

    this.setState({isLeftSide: (!this.state.isLeftSide)}, () => {
       this.animate();
    });
    

    setState 完成后接受回调。

    我玩了一段时间的小吃,问题显然是状态不同步,因为它说的是在左边,而实际上在右边。我看不出有什么其他东西在搅乱这个国家。

    你可以在这里看到它:https://snack.expo.io/BJhb4-pAW

    小吃在某种程度上是有限的,所以你可以在你的代码上试试这个吗?

     finishedAnimation = (finished) => {
        if (finished)
          this.setState({isLeftSide: !(this.state.isLeftSide)});
      }
    
      fire = () => { 
         this.animatedValue.setValue(0);
        Animated.timing(
          this.animatedValue,
          {
            toValue: 1,
            duration: 300,
            easing: Easing.linear
          }
        ).start(this.finishedAnimation);
      }
    

    【讨论】:

    • 仍然,它从左侧开始,然后向右跳并一直向左滑动(初始运行时)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2016-08-02
    • 2020-11-08
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多