【问题标题】:How should I animate a React native component with the library "Animated"我应该如何使用“动画”库为 React 原生组件制作动画
【发布时间】:2019-05-25 01:34:10
【问题描述】:

我正在尝试为某些组件设置动画。我只想更改视图宽度的大小。我一直在寻找制作简单动画的最简单方法。我正在使用“Animated”库。我无法完成这项工作

我正在寻找一些教程,但它不起作用。由于某种原因,代码没有重新调整“Animated.View”的初始宽度,它是在构造函数上声明的变量,就像这个“animationwidth = new Animated.Value(11);"。不知道问题出在变量的声明、“Animated.View”的样式还是“animated.timing”函数中

import React, { Component } from 'react';
import {Animated,Text,Alert,View, Image, Button} from 'react-native';

export default class Game extends Component {
    constructor(props) {
        super(props);
        this.state = {
            opa: 1
        };
        animationwidth = new Animated.Value(11);

    }
    componentDidmount(){
        Animated.timing(this.animationwidth, {
            toValue: 300
        }).start()
    }

    render(){
        return(
            <View style={{flex:1,alignItems:'center',backgroundColor:'green',justifyContent:'center'}}>
                <Animated.View style={{ height:250, width:this.animationwidth ,backgroundColor:'blue'}}/>
            </View>
        )
    }
}

【问题讨论】:

    标签: react-native animation


    【解决方案1】:

    您忘记在动画宽度中包含状态:

    像这样改变你的 Animated.View 组件样式:

    <Animated.View style={{ height:250, width:this.state.animationwidth ,backgroundColor:'blue'}}/>
    

    如果没有动画。在动画计时函数中添加持续时间属性,并将状态添加到动画宽度,如下所示:

            Animated.timing(this.state.animationwidth, {
            toValue: 300,
            duration: 1000
        }).start()
    }
    

    根据您的代码,您的视图宽度将从 11 开始,以 300 结束

    【讨论】:

    • 我在当前 View 之前共享的代码的宽度 = 0 ,它甚至无法识别初始宽度 = 11。现在我已经按照您所说的更改了代码,现在它可以识别了最初的witdh,但它并没有变大,它只是停留在11,就像它没有任何动画一样。
    • 我忘记了,尝试移动动画宽度:新动画。值(11);内部状态
    • 我做了,状态是这样的:this.state = {animationwidth : new Animated.Value(11) };我像这样调用animated.timing:Animated.timing(this.state.animationwidth, { toValue: 300, duration: 1000 }).start() 和animated.view是这样的:
    • 我想通了。将 componentDidmount 更改为“componentDidMount”生命周期方法应该是驼峰式的。 :D
    • 是的,它成功了。我没有看到那个小而重要的细节,非常感谢。!!!
    【解决方案2】:

    这里的问题是没有再次调用渲染方法,因为状态没有再次更新。您需要更新 componentDidmount 中的一些状态变量,因此 render 方法将再次调用。 添加一个状态变量并在 componentDidMount 中切换该变量

        this.state = {
            isShowing : false
        };
    
        componentDidmount(){
          this.setState({isShowing:!this.state.isShowing})
          Animated.timing(this.animationwidth, {
            toValue: 300
          }).start()
        }
    

    【讨论】:

      猜你喜欢
      • 2017-07-31
      • 2012-09-27
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多