我目前正在学习使用RN Reanimated和Redash库创建React Native动画。我已经设法创建了一个简单的计时动画,它将一个TextInput占位符转换为一个标签。
import Animated, { Clock, Easing, set, useCode } from 'react-native-reanimated';
import { timing } from 'react-native-redash/lib/module/v1';
const [isFocused, setIsFocused] = useState(false);
const clock = new Clock();
const [animation] = useState(new Animated.Value(0));
const shouldAnimateLabel = isFocused || !!value;
useCode(() =>
set(
animation,
timing({
clock,
animation,
duration: 150,
from: shouldAnimateLabel ? 0 : 1,
to: shouldAnimateLabel ? 1 : 0,
easing: Easing.inOut(Easing.ease),
}),
[shouldAnimateLabel],
),
);
const animatedStyles = {
top: Animated.interpolate(animation, {
inputRange: [0, 1],
outputRange: [20, -5],
}),
fontSize: Animated.interpolate(animation, {
inputRange: [0, 1],
outputRange: [18, 14],
}),
color: Animated.interpolateColors(animation, {
inputRange: [0, 1],
outputColorRange: ['#aaa', '#fff'],
}),
};这个动画在聚焦/模糊输入时工作得很好,但是当useCode在挂载时运行时,在我与任何一个输入交互之前,我就得到了标签从1动画到0动画的不想要的副作用。

有没有使用react-native-reanimated或react-native-redash的通用解决方案?我可以添加另一个isMounted状态或其他东西,但这似乎是一个笨拙的解决方案?
发布于 2020-10-12 15:38:16
可能是这样的:
import Animated, { Clock, Easing, set, useCode } from 'react-native-reanimated';
import { timing } from 'react-native-redash/lib/module/v1';
const [isFocused, setIsFocused] = useState(null);
const clock = new Clock();
const [animation] = useState(new Animated.Value(0));
const shouldAnimateLabel = isFocused === null ? null : isFocused || !!value;
useCode(() =>
set(
animation,
timing({
clock,
animation,
duration: 150,
from: shouldAnimateLabel ? 0 : 1,
to: shouldAnimateLabel || shouldAnimateLabel === null ? 1 : 0,
easing: Easing.inOut(Easing.ease),
}),
[shouldAnimateLabel],
),
);
const animatedStyles = {
top: Animated.interpolate(animation, {
inputRange: [0, 1],
outputRange: [20, -5],
}),
fontSize: Animated.interpolate(animation, {
inputRange: [0, 1],
outputRange: [18, 14],
}),
color: Animated.interpolateColors(animation, {
inputRange: [0, 1],
outputColorRange: ['#aaa', '#fff'],
}),
};https://stackoverflow.com/questions/64205977
复制相似问题