React Native的动画(二)

作者: oceanLong | 来源:发表于2017-05-31 00:51 被阅读50次

前言

上一节中,介绍了React Native的LayoutAnimation。LayoutAnimation可以用来开发简单的动画。但面对组合动画的开发,就不那么方便了。因此,在React Native中还有一个Animated来完成复杂动画的开发。

Animated

Animated类似于一个单纯的值动画类。它本身并不完成任何动画的功能实现。我们通常将它设进state中。然后在合适的时机,调用Animated.timing().start()来开始执行动画。动画本身,以参数的形式传入timing方法中。如下面的代码所示:我们在创建Animated时,传入初始值为0。然后将timing中的动画定义为目标值为1。时间设定为3000ms。

  constructor(props){
     super(props);
     this.state={
      fadeAnim: new Animated.Value(0),
    };
  }
  // 在组件渲染完成之后执行
  componentDidMount(){
    Animated.timing(
      this.state.fadeAnim,{
        toValue:1,
        duration:3000,
      }
    ).start();

  }

将下来,我们只需要,将我们的某个ui与state中的fadeAnim关联起来即可。

一个例子

创建一个在渲染时,会渐进显示的控件。渐进时间是3秒,透明度由0到1。

import React ,{Component} from 'react';
import{
  Animated,
} from 'react-native'

export default class FadeInView extends Component{

  constructor(props){
     super(props);
     this.state={
      fadeAnim: new Animated.Value(0),
    };
  }
  // 在组件渲染完成之后执行
  componentDidMount(){
    Animated.timing(
      this.state.fadeAnim,{
        toValue:1,
        duration:3000,
      }
    ).start();

  }
  render(){
    return (
      <Animated.View
      style={{
         ...this.props.style,
         opacity: this.state.fadeAnim,          // 将透明度指定为动画变量值
       }}>
       {this.props.children}
     </Animated.View>
   );
  }
}

一些坑

在React Native Android中,需要做一些全局设置。

const { UIManager } = NativeModules;

UIManager.setLayoutAnimationEnabledExperimental &&
  UIManager.setLayoutAnimationEnabledExperimental(true);

参考资料:reactnative.cn

如有问题,欢迎指正。

相关文章

网友评论

    本文标题:React Native的动画(二)

    本文链接:https://www.haomeiwen.com/subject/zcddfxtx.html