仅在 TextInput 焦点/模糊上运行 Reanimated 动画

Con*_*son 5 javascript react-native react-native-reanimated

我目前正在学习使用 RN ReanimatedRedash库创建 React Native Animations 。我设法创建了一个简单的定时动画,它将 TextInput 占位符转换为标签。

  import Animated, { Clock, Easing, set, useCode } from 'react-native-reanimated';
  import { timing } from 'react-native-redash/lib/module/v1';

  const [isFocused, setIsFocused] = useState(false);
  const clock = new Clock();
  const [animation] = useState(new Animated.Value(0));
  const shouldAnimateLabel = isFocused || !!value;

  useCode(() =>
    set(
      animation,
      timing({
        clock,
        animation,
        duration: 150,
        from: shouldAnimateLabel ? 0 : 1,
        to: shouldAnimateLabel ? 1 : 0,
        easing: Easing.inOut(Easing.ease),
      }),
      [shouldAnimateLabel],
    ),
  );

  const animatedStyles = {
    top: Animated.interpolate(animation, {
      inputRange: [0, 1],
      outputRange: [20, -5],
    }),
    fontSize: Animated.interpolate(animation, {
      inputRange: [0, 1],
      outputRange: [18, 14],
    }),
    color: Animated.interpolateColors(animation, {
      inputRange: [0, 1],
      outputColorRange: ['#aaa', '#fff'],
    }),
  };
Run Code Online (Sandbox Code Playgroud)

聚焦/模糊输入时,此动画工作正常,但由于useCode上安装运行,我目前正从标签动画的不良副作用10之前,我曾与其中一个输入交互。

在此处输入图片说明

使用react-native-reanimatedor有没有通用的解决方案react-native-redash?我可以添加另一个isMounted状态或其他东西,但这似乎是一个笨拙的解决方案?

小智 0

也许是这样的:

import Animated, { Clock, Easing, set, useCode } from 'react-native-reanimated';
import { timing } from 'react-native-redash/lib/module/v1';

const [isFocused, setIsFocused] = useState(null);
const clock = new Clock();
const [animation] = useState(new Animated.Value(0));
const shouldAnimateLabel = isFocused === null ? null : isFocused || !!value;

useCode(() =>
  set(
    animation,
    timing({
      clock,
      animation,
      duration: 150,
      from: shouldAnimateLabel ? 0 : 1,
      to: shouldAnimateLabel || shouldAnimateLabel === null ? 1 : 0,
      easing: Easing.inOut(Easing.ease),
    }),
    [shouldAnimateLabel],
  ),
);

const animatedStyles = {
  top: Animated.interpolate(animation, {
    inputRange: [0, 1],
    outputRange: [20, -5],
  }),
  fontSize: Animated.interpolate(animation, {
    inputRange: [0, 1],
    outputRange: [18, 14],
  }),
  color: Animated.interpolateColors(animation, {
    inputRange: [0, 1],
    outputColorRange: ['#aaa', '#fff'],
  }),
};
Run Code Online (Sandbox Code Playgroud)