我正在尝试创建一个保存按钮(基本上是为屏幕添加书签),无论用户点击按钮以“保存”项目还是删除“保存”,它都会切换动画。点击按钮应该调用其中一个动画,无论它是“on”动画还是“off”动画。
不幸的是,除了 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);