看看下面的自定义Switch组件,该组件演示了本机驱动程序动画存在的问题。如果开关在关闭状态下安装,先更改为打开,然后再卸载,动画将在卸载之前将其重置为关闭(不通过调用渲染)。禁用本机驱动程序似乎可以解决问题。
import React, { Component } from 'react';
import { Animated, TouchableOpacity } from 'react-native';
export default class Switch extends Component {
constructor(props) {
super(props);
this.state = {
isOn: props.value, // Use state instead of props for responsiveness
translateX: new Animated.Value(props.value ? 20 : 0),
};
}
_onPress = () => {
const { isOn, translateX } = this.state;
const { onValueChange } = this.props;
this.setState({ isOn: !isOn }, () => {
onValueChange(!isOn);
Animated.spring(translateX, {
toValue: isOn ? 0 : 20,
friction: 5,
tension: 40,
useNativeDriver: true, // Set this to false to fix unmounting re-draw
}).start();
});
}
render() {
const { isOn, translateX } = this.state;
return (<TouchableOpacity onPress={this._onPress} style={{ borderWidth: 1, borderColor: 'rgba(255,255,255,0.8)', width: 45, height: 25, borderRadius: 20, justifyContent: 'center' }} activeOpacity={0.7}><Animated.View style={{ backgroundColor: 'rgba(255,255,255,0.8)', width: 20, height: 20, borderRadius: 25, marginHorizontal: 1, transform: [{ translateX }] }} useNativeDriver /></TouchableOpacity>);
}
}