【发布时间】:2026-01-22 03:45:02
【问题描述】:
我正在使用动画 API import { Animated } from 'react-native'
在样式中指定width: animated-value 时,width 实际上只渲染一次,并且不会动态更改。如果您使元素重新渲染,您只能看到幕后的动画值正在发生变化。
// since only function components can use hooks, wrap the classical component in a function one
// that sets up the hook for it
function withAnimationHook(Component) {
return function WrappedComponent(props) {
const anim = useRef(new Animated.Value(0));
useEffect(() => {
Animated.loop(
Animated.sequence([
Animated.timing(anim.current, {
toValue: 1,
duration: 2000,
}),
Animated.timing(anim.current, {
toValue: 0,
duration: 2000,
}),
])
).start();
}, []);
return <Component {...props} anim={anim} />;
}
}
class AnimatedButton extends React.Component {
render() {
const { anim, width } = this.props
return (
<Animated.View style={{ width: width * anim.current._value }}>
</Animated.View>
)
}
}
export default withAnimationHook(AnimatedButton)
我知道设置动画值是可行的,因为 style={{ transform: [{ scale: anim.current }] }} 可以完美运行(它会反复增长和缩小)。
为什么width: width * anim.current._value 不对宽度设置动画?
如何为宽度设置动画?
this.props.width 只是一个数字,例如64
【问题讨论】:
标签: javascript react-native react-native-web