首页 > 解决方案 > 在本机反应中使动画连续

问题描述

在这里,我正在为一个图标设置动画,但我需要它不断旋转。我能够让它旋转,但它停止了。我不确定如何更改它以使其不断旋转。它会旋转一点,但不会连续旋转。

import React, { useRef } from 'react';
import { Animated, Easing, StyleProp, TextStyle } from 'react-native';
import useMountEffect from '../../../common/hook/useMountEffect';
import Icon from '../../../common/icon/Icon/Icon';

interface Props {
  name: string;
  size?: number;
  color?: string;
  style?: StyleProp<TextStyle>;
  variant?: 'solid' | 'brand' | 'light';
}

const SpinningIcon: React.FC<Props> = ({
  name,
  size,
  color,
  style,
  variant,
}) => {
  const spinValue = useRef(new Animated.Value(0));
  useMountEffect(() => {
    Animated.timing(spinValue.current, {
      toValue: 1,
      duration: 1000,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start();
  });

  const rotate = spinValue.current.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  return (
    <Animated.View style={{ transform: [{ rotate }] }}>
      <Icon
        size={size}
        color={color}
        name={name}
        style={style}
        variant={variant}
      />
    </Animated.View>
  );
};

export default SpinningIcon;

标签: iosreact-native

解决方案


您可以使用Animated.loop()

import React, { useRef } from 'react';
import { Animated, Easing, StyleProp, TextStyle } from 'react-native';
import useMountEffect from '../../../common/hook/useMountEffect';
import Icon from '../../../common/icon/Icon/Icon';

interface Props {
  name: string;
  size?: number;
  color?: string;
  style?: StyleProp<TextStyle>;
  variant?: 'solid' | 'brand' | 'light';
}

const SpinningIcon: React.FC<Props> = ({
  name,
  size,
  color,
  style,
  variant,
}) => {
  const spinValue = useRef(new Animated.Value(0));
  useMountEffect(() => {
    Animated.loop(
      Animated.timing(spinValue.current, {
        toValue: 1,
        duration: 1000,
        easing: Easing.linear,
        useNativeDriver: true,
      }),
    ).start();
  });

  const rotate = spinValue.current.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  return (
    <Animated.View style={{ transform: [{ rotate }] }}>
      <Icon
        size={size}
        color={color}
        name={name}
        style={style}
        variant={variant}
      />
    </Animated.View>
  );
};

export default SpinningIcon;

推荐阅读