我有一個反應功能組件Svg被用作底部標簽欄的圖示。在路線更改時,將當前state.index與路線進行比較index。本質上是布爾狀態的結果isFocused被傳遞給 Svg。
我正在嘗試根據此狀態為 Svg 設定影片,但無法使用 reanimated 完成簡單操作。我最確定 fill 的值不會在useAnimatedPropshook中更新,但我缺乏對 reanimated 有深入了解的經驗。任何幫助將不勝感激
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>
);
};
uj5u.com熱心網友回復:
更常見的方法是使用“進度變數”作為共享值。
const fillProgress = useSharedValue(isFocused? 1 : 0);
您將使用此進度變數來生成影片道具。請注意使用interpolateColor來獲取實際的插值顏色。
const animatedProps = useAnimatedProps(() => {
const fillValue = interpolateColor(fillProgress.value, [0, 1], ["transparent", "red"]);
return {
fill: fillValue
}
});
您必須回傳一個具有您想要設定影片的屬性的物件。例如,如果您想為填充和不透明度設定影片,您將回傳{fill: "", opacity: -1}適當的值而不是""和-1。最后,您必須制作要影片的實際元素 Animated。在這種情況下,您希望為 設定影片Circle,而不是設定為SvgAnimated 物件。
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
然后,您可以使用useEffect并相應地進行影片檢測。
useEffect(() => {
fillProgress.value = withTiming(isFocused? 1 : 0);
}, [isFocused]);
請記住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>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401031.html
