首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >仅在TextInput焦点/模糊上运行重动画

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

Stack Overflow用户
提问于 2020-10-05 17:31:18
回答 1查看 534关注 0票数 5

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

代码语言:javascript
复制
  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'],
    }),
  };

这个动画在聚焦/模糊输入时工作得很好,但是当useCode在挂载时运行时,在我与任何一个输入交互之前,我就得到了标签从1动画到0动画的不想要的副作用。

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

EN

回答 1

Stack Overflow用户

发布于 2020-10-12 15:38:16

可能是这样的:

代码语言:javascript
复制
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'],
  }),
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64205977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档