You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ReAnimated对Icon进行颜色插值动画?

用Reanimated实现Hero Icon的颜色平滑过渡

方案一:包装Hero Icon为动画组件

Reanimated没有内置支持Hero Icon组件,直接用Animated.createAnimatedComponent将其转换为可动画组件,之后就能绑定动画值到color属性实现平滑过渡:

import Animated from 'react-native-reanimated';
import { HeartIcon } from '@heroicons/react-native';

// 生成动画版的Hero Icon
const AnimatedHeartIcon = Animated.createAnimatedComponent(HeartIcon);

function AnimatedIconExample() {
  // 初始化颜色动画值
  const colorAnim = Animated.useSharedValue('#000');

  // 触发颜色过渡动画
  const triggerColorChange = () => {
    colorAnim.value = Animated.timing(colorAnim, {
      toValue: '#ff4444',
      duration: 600,
      useNativeDriver: false, // 颜色动画不支持原生驱动
    }).start();
  };

  return (
    <AnimatedHeartIcon
      size={28}
      color={colorAnim}
      onPress={triggerColorChange}
    />
  );
}

方案二:通过父容器动画传递颜色

如果你的Hero Icon支持继承父组件的文本颜色,可以用Animated.View作为容器,把动画值绑定到容器的color样式上:

import Animated from 'react-native-reanimated';
import { HeartIcon } from '@heroicons/react-native';

function AnimatedIconExample() {
  const colorAnim = Animated.useSharedValue('#000');

  const triggerColorChange = () => {
    colorAnim.value = Animated.timing(colorAnim, {
      toValue: '#ff4444',
      duration: 600,
      useNativeDriver: false,
    }).start();
  };

  const animatedStyle = Animated.useAnimatedStyle(() => ({
    color: colorAnim.value,
  }));

  return (
    <Animated.View style={animatedStyle} onPress={triggerColorChange}>
      <HeartIcon size={28} />
    </Animated.View>
  );
}

注意:颜色动画无法使用Reanimated的原生驱动,必须将useNativeDriver设为false。

内容的提问来源于stack exchange,提问作者Cole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 15:50:15