React Native - 动画


在本章中,我们将向您展示如何在 React Native 中使用LayoutAnimation

动画组件

我们将把myStyle设置为状态的一个属性。此属性用于为PresentationalAnimationComponent内的元素设置样式。

我们还将创建两个函数 - ExpandElementCollapseElement。这些函数将更新状态值。第一个将使用弹簧预设动画,而第二个将使用线性预设。我们也将把它们作为道具传递。Expand和Collapse按钮​​调用expandElement()和collapseElement ( )函数。

在此示例中,我们将动态更改框的宽度和高度。由于Home组件是相同的,我们将只更改Animations组件。

应用程序.js

import React, { Component } from 'react'
import { View, StyleSheet, Animated, TouchableOpacity } from 'react-native'

class Animations extends Component {
   componentWillMount = () => {
      this.animatedWidth = new Animated.Value(50)
      this.animatedHeight = new Animated.Value(100)
   }
   animatedBox = () => {
      Animated.timing(this.animatedWidth, {
         toValue: 200,
         duration: 1000
      }).start()
      Animated.timing(this.animatedHeight, {
         toValue: 500,
         duration: 500
      }).start()
   }
   render() {
      const animatedStyle = { width: this.animatedWidth, height: this.animatedHeight }
      return (
         <TouchableOpacity style = {styles.container} onPress = {this.animatedBox}>
            <Animated.View style = {[styles.box, animatedStyle]}/>
         </TouchableOpacity>
      )
   }
}
export default Animations

const styles = StyleSheet.create({
   container: {
      justifyContent: 'center',
      alignItems: 'center'
   },
   box: {
      backgroundColor: 'blue',
      width: 50,
      height: 100
   }
})