React Native - 動畫



在本章中,我們將展示如何在 React Native 中使用 LayoutAnimation

動畫元件

我們將把 myStyle 作為狀態的一個屬性設定。此屬性用於對 PresentationalAnimationComponent 中的元素進行樣式設定。

我們還將建立兩個函式 - expandElementcollapseElement。這些函式將更新狀態中的值。第一個將使用 spring 預設動畫,而第二個將具有 linear 預設。我們也將這些作為屬性傳遞。ExpandCollapse 按鈕呼叫了 expandElement()collapseElement() 函式。

在此示例中,我們將動態更改框的寬度和高度。因為 Home 元件將保持不變,所以我們只會更改 Animations 元件。

App.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
   }
})
廣告