如何使用Lottie在React Native中在运行时切换动画?

时间:2017-11-14 18:05:01

标签: react-native lottie

我正在尝试创建一个保存按钮(基本上是为屏幕添加书签),无论用户点击按钮以“保存”某个项目还是删除“保存”,都会切换动画。点击该按钮应调用其中一个动画,无论是“开”动画还是“关闭”动画。

不幸的是,除了iOS之外,我找不到任何关于在React Native中按钮上切换动画的文档。任何想法都将不胜感激。

这是组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
    StyleSheet,
    TouchableOpacity
} from 'react-native';
import _ from 'lodash';

import { connect } from 'react-redux';
import { toggleSaved } from '../../actions';
import Animation from 'lottie-react-native';

import onAnimation from '../animations/heart_On.json';
import offAnimation from '../animations/heart_Off.json';

class SaveButton extends Component {
    isSaved = () => {
        let item = this.props.item;
        if (_.find(this.props.saved, function(i) { return i.type == item.type && i.id == item.id; })) {
            return true;
        } else {
            return false;
        }
    }

    toggleSaved = (saved, item) => {
        const { dispatch } = this.props;
        dispatch(toggleSaved(saved, item));
        this.animation.play();
    }

    render() {
        return (
            <TouchableOpacity
                onPress={ () => this.toggleSaved(this.props.saved, this.props.item) }
            >
                <Animation
                    ref={ animation => {
                        this.animation = animation;
                    } }
                    style={ styles.icon }
                    loop={ false }
                    source={ this.isSaved() ? onAnimation: offAnimation }
                />
            </TouchableOpacity>
        );
    }
}

SaveButton.propTypes = {
    dispatch: PropTypes.func.isRequired,
    saved: PropTypes.array.isRequired,
    item: PropTypes.object.isRequired
};

const styles = StyleSheet.create({
    icon: {
        width: 30,
        height: 30,
        marginTop: 5,
        marginRight: 10
    }
});

function mapStateToProps(state) {
    const { saved } = state.saved;

    return {
        saved
    };
}

export default connect(mapStateToProps)(SaveButton);

1 个答案:

答案 0 :(得分:1)

我建议你有两个独立的动画元素,然后根据状态显示或隐藏(当然还有.play())。

所以(半假的代码得到了想法):

  • 状态道具isSaved,用于定义当前在舞台上的动画
  • 保存(或删除)切换状态以显示正确的动画并调用this.refToCorrectAnimation.play()
constructor(props) {
  super(props);
  this.state = {
    isSaved: false,
  };
}

isSavedVisible() {
  return (this.state.isSaved) ? { display: 'flex' } : { display: 'none' };
}

isRemovedVisible() {
  return (!this.state.isSaved) ? { display: 'flex' } : { display: 'none' };
}


toggleSaved(...) {
  if (this.state.isSaved) {
    this.isSavedAnimation.play();
  } else {
    this.isRemovedAnimation.play();
}

render() {
  return (
    <TouchableOpacity onPress={() => this.toggleSaved()} ...>
      <Animation style={this.isSavedVisible()} ref={(animation) = this.isSavedAnimation = animation} ... />
      <Animation style={this.isRemovedVisible()} ref={(animation) = this.isRemovedAnimation = animation} ... />
    </TouchableOpacity>
  )
}