我目前正在学习使用 RN Reanimated 创建 React Native 动画。和 Redash图书馆。我设法创建了一个简单的计时动画,它将 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
状态或其他东西,但这似乎是一个笨重的解决方案?
最佳答案
也许是这样的:
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'],
}),
};
关于javascript - 仅在 TextInput 焦点/模糊上运行 Reanimated 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64205977/