Ash*_*Ash 1 react-native react-native-reanimated-v2
我有一个反应功能组件Svg用作 Bottom-TabBar 的图标。在路线更改时,将当前路线state.index与路线进行比较index。结果本质上是一个布尔状态,isFocused被传递到 Svg。
我正在尝试根据此状态对 Svg 进行动画处理,但无法使用重新动画完成简单的操作。我最确定的是,填充的值没有在useAnimatedProps钩子中更新,但我缺乏对复活有深入了解的经验。任何帮助将不胜感激
import Animated, {
useAnimatedProps,
useSharedValue,
} from 'react-native-reanimated';
import Svg, { Circle, Path } from 'react-native-svg';
const AnimatedSvg = Animated.createAnimatedComponent(Svg);
export default ({ isFocused }) => {
const fill = useSharedValue({ fill: 'transparent' });
const animatedProps = useAnimatedProps(() => {
isFocused
? (fill.value = { fill: 'red' })
: (fill.value = { fill: 'transparent' });
return fill.value;
});
return (
<AnimatedSvg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
animatedProps={animatedProps}
stroke={'white'}
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className="feather feather-search">
<Circle cx={11} cy={11} r={8} />
<Path d="m21 21-4.35-4.35" />
</AnimatedSvg>
);
};
Run Code Online (Sandbox Code Playgroud)
小智 5
更常见的方法是使用“进度变量”作为共享值。
const fillProgress = useSharedValue(isFocused? 1 : 0);
Run Code Online (Sandbox Code Playgroud)
您可以使用此进度变量来生成动画道具。请注意使用 来interpolateColor获取实际的插值颜色。
const animatedProps = useAnimatedProps(() => {
const fillValue = interpolateColor(fillProgress.value, [0, 1], ["transparent", "red"]);
return {
fill: fillValue
}
});
Run Code Online (Sandbox Code Playgroud)
您必须返回一个具有您想要设置动画的属性的对象。例如,如果您想要对填充和不透明度进行动画处理,您将返回{fill: "", opacity: -1}适当的值而不是""和-1。最后,您必须将要设置动画的实际元素制作为动画。在本例中,您想要对 进行动画处理Circle,而不是对Svg进行动画处理,因此它必须是一个动画对象。
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用检测到焦点useEffect并相应地设置动画。
useEffect(() => {
fillProgress.value = withTiming(isFocused? 1 : 0);
}, [isFocused]);
Run Code Online (Sandbox Code Playgroud)
fillProgress请记住像在函数中一样设置初始值withTiming。
总而言之,您必须对使用动画属性的元素进行动画处理,并且您应该使用上面提到的进度变量。
以下是完整修改后的代码(在 Android 上测试):
import Animated, {
useAnimatedProps,
useSharedValue,
} from 'react-native-reanimated';
import Svg, { Circle, Path } from 'react-native-svg';
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
export default function Icon ({ isFocused }) {
const fillProgress = useSharedValue(isFocused? 1 : 0);
const animatedProps = useAnimatedProps(() => {
const fillValue = interpolateColor(fillProgress.value, [0, 1], ["transparent", "red"]);
return {
fill: fillValue
}
});
useEffect(() => {
fillProgress.value = withTiming(isFocused? 1 : 0);
}, [isFocused]);
return (
<Svg
width={24}
height={24}
stroke={'white'}
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className="feather feather-search">
<AnimatedCircle animatedProps={animatedProps} cx={11} cy={11} r={8} />
<Path d="m21 21-4.35-4.35" />
</Svg>
);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4432 次 |
| 最近记录: |