对值集进行反应本机重置的动画重置

时间:2020-01-22 17:52:39

标签: javascript typescript react-native animation react-native-reanimated

我想做什么?

我正在尝试使用react-native-reanimated为应用中的标题设置动画。

直到现在我一直在做什么?

我已经对动画进行了编码,但是当我尝试将动画重新设置为原始值时,动画会重置。

代码

import React, { useContext } from 'react';
import Reanimated, { Easing, Extrapolate } from 'react-native-reanimated';
import PacientCategoryButton from '../PacientCategoryButton';
import PacientCategoryIndexContext from './contex';
import { Container } from './styles';

const {
  Value,
  Clock,
  createAnimatedComponent,
  interpolate,
  block,
  cond,
  clockRunning,
  set,
  startClock,
  stopClock,
  useCode,
  timing,
  onChange
} = Reanimated;

const AnimatedContainer = createAnimatedComponent(Container);

export interface PacientCategorySelectorProps {
  setIndex: React.Dispatch<React.SetStateAction<number>>;
}

function runTiming(
  clock: Reanimated.Clock,
  value: Reanimated.Value<number>,
  config: Reanimated.TimingConfig
) {
  const state = {
    finished: new Value(0),
    position: new Value(0),
    time: new Value(0),
    frameTime: new Value(0)
  };

  return block([
    onChange(config.toValue, set(state.frameTime, 0)),
    cond(clockRunning(clock), 0, [
      set(state.finished, 0),
      set(state.time, 0),
      set(state.position, value),
      set(state.frameTime, 0),
      startClock(clock)
    ]),
    timing(clock, state, config),
    cond(state.finished, stopClock(clock)),
    state.position
  ]);
}

const PacientCategorySelector = ({
  setIndex
}: PacientCategorySelectorProps) => {
  const currentIndex = useContext(PacientCategoryIndexContext);
  const animation = new Value<number>(0);
  const translateX = interpolate(animation, {
    inputRange: [0, 1],
    outputRange: [64, -64],
    extrapolate: Extrapolate.EXTEND
  });

  useCode(
    () => [
      set(
        animation,
        runTiming(new Clock(), animation, {
          duration: 270,
          easing: Easing.inOut(Easing.ease),
          toValue: currentIndex
        })
      )
    ],
    [currentIndex]
  );

  return (
    <AnimatedContainer style={{ transform: [{ translateX }] }}>
      <PacientCategoryButton index={0} setIndex={setIndex} label="Hoje" />
      <PacientCategoryButton index={1} setIndex={setIndex} label="Todos" />
    </AnimatedContainer>
  );
};

export default PacientCategorySelector;

结果

https://youtu.be/sT96_lp_WqM

0 个答案:

没有答案