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



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

不幸的是,除了 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);

我建议您有两个单独的动画元素,然后根据状态相应地显示或隐藏(当然还有.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>
  )
}

相关内容

  • 没有找到相关文章

最新更新