масштабирование нативной кнопки с анимированным

Я создаю сенсорную кнопку в React Native с анимацией. Когда кнопка нажата, она должна немного уменьшиться. Когда давление сбрасывается, оно должно вернуться к норме.

Это мой код:

export const TouchableButton = (props) => {

    const { onPress, text, icon } = props

    const animatedValue = new Animated.Value(0)

    const animatedValueInterpolateScale = animatedValue.interpolate({
        inputRange: [0, 1],
        outputRange: [1, 0.95]
    })

    const pressInHandler = () => {
        Animated.timing(
            animatedValue,
            {
                toValue: 1,
                duration: 150
            }
        ).start()
    }

    const pressOutHandler = () => {
        Animated.timing(
            animatedValue,
            {
                toValue: 0,
                duration: 150
            }
        ).start()
    }

return (
    <TouchableWithoutFeedback onPress={onPress} onPressIn={pressInHandler} onPressOut={pressOutHandler}>
        <View style={{ alignItems: 'center' }}>
            <Animated.View style={{ width: '100%', height: 40, borderRadius: 5, overflow: 'hidden', transform: [{ scaleX: animatedValueInterpolateScale }, { scaleY: animatedValueInterpolateScale }] }}>
                <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: Color.GrayLight }}>
                    <Text style={{ marginTop: 2.5, fontFamily: 'AlegreyaSans-Medium', fontSize: 15, color: Color.White }}>{text}</Text>
                    <View style={{ position: 'absolute', left: 12.5, top: 12.5 }}>
                        <Icon lib={icon.lib} icon={icon.icon} color={Color.White} size={15} />
                    </View>
                </View>
            </Animated.View>
        </View>
    </TouchableWithoutFeedback>
)
}

При нажатии кнопки запускается анимация в pressInHandler, и масштаб анимируется от 1 до 0,95. Это работает. Но когда я отпускаю давление (вызывается onPressOut), масштаб возвращается к 1 без плавной анимации. Кажется, что pressOutHandler (и анимация в нем) никогда не вызывается.

У меня есть другая кнопка с такими же свойствами, но вместо масштабирования я задаю цвет фона, и это работает как надо.


person yesterday    schedule 20.05.2020    source источник


Ответы (1)


Упрости.

Примечание. ВСЕГДА ИСПОЛЬЗУЙТЕ useNativeDriver: true

const App = () => {
  const animation = new Animated.Value(0);
  const inputRange = [0, 1];
  const outputRange = [1, 0.8];
  const scale = animation.interpolate({inputRange, outputRange});

  const onPressIn = () => {
    Animated.spring(animation, {
      toValue: 1,
      useNativeDriver: true,
    }).start();
  };
  const onPressOut = () => {
    Animated.spring(animation, {
      toValue: 0,
      useNativeDriver: true,
    }).start();
  };

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.button, {transform: [{scale}]}]}>
        <TouchableOpacity
          style={styles.btn}
          activeOpacity={1}
          onPressIn={onPressIn}
          onPressOut={onPressOut}>
          <Text style={styles.btnText}>BUTTON</Text>
        </TouchableOpacity>
      </Animated.View>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {flex: 1, alignItems: 'center', justifyContent: 'center'},
  button: {
    height: 70,
    width: 200,
    backgroundColor: 'red',
    marginBottom: 20,
    borderRadius: 10,
  },
  btn: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  btnText: {
    color: '#fff',
    fontSize: 25,
  },
});
person Aswin C    schedule 20.05.2020