是否使用 useState 来反应原生动画 => new Animated.Value() ?

问题描述 投票:0回答:4

在react-native中使用Animated.Value()的最佳方式是什么?

是否使用 useState() ?

const [fadeAnim] = useState(new Animated.Value(0))

或者

const fadeAnim = new Animated.Value(0)

React-native 文档:https://facebook.github.io/react-native/docs/animations

谢谢

react-native react-hooks
4个回答
7
投票

我最近一直在用这个:

const [fadeAnim] = useState(() => new Animated.Value(0));

设定值标准:

fadeAnim.setValue(0);

此外,您可能还想查看

useRef
,因为这是文档推荐的:

const fadeAnim = useRef(new Animated.Value(0)).current;
/* 
... 
*/
fadeAnim.setValue(0);

4
投票

实际上,Hook 是更好的方法,所以我会说首选


3
投票

我遇到了一个狡猾的 UI 错误,其中设置挂钩值会立即在视图中呈现并弄乱动画。我通过将动画值放入 useState 挂钩中来修复此问题,如下所示:

之前:

const foo = new Animated.Value(1)

之后:

  const [foo] = useState(new Animated.Value(1));

1
投票

按照

中的建议使用
useRef()

https://reactnative.dev/docs/animated

https://reactnative.dev/docs/animations#animated-api

const [fadeAnim] = useState(() => new Animated.Value(0));

它是相同的,但语义上

"state"
意味着
getter
setter
- 没有
setter
'fadeAnim'
在整个组件的生命周期中都是相同的,所以与
useRef(...).current

没有什么不同
© www.soinside.com 2019 - 2024. All rights reserved.