React Native中使用useAnimatedValue报错:TypeError: (0 , _index.useAnimatedValue) is not a function
React Native中使用useAnimatedValue报错:TypeError: (0 , _index.useAnimatedValue) is not a function
嘿,这个问题我之前刚踩过类似的坑,咱们来一步步解决它~
首先得给你划个重点:useAnimatedValue根本不是React Native原生Animated库的API!你从react-native里导入它,自然会报“不是函数”的错,它其实是react-native-reanimated这个第三方动画库的专属钩子。
接下来给你具体的解决步骤:
第一步:先确认有没有安装
react-native-reanimated
如果还没装,赶紧用包管理器安装:- npm的话执行:
npm install react-native-reanimated - yarn的话执行:
yarn add react-native-reanimated
要是你用的是iOS项目,安装完记得cd到ios目录跑一下pod install,Android的话0.60+版本会自动链接,不用额外操作。
- npm的话执行:
第二步:修正导入语句
把你原来的导入代码:import { Animated, useAnimatedValue } from "react-native";改成:
import { Animated } from "react-native"; import { useAnimatedValue } from "react-native-reanimated";第三步:注意Reanimated版本的差异
如果你装的是Reanimated v2及以上的新版本,其实useAnimatedValue已经被废弃了,官方推荐用useSharedValue来替代,而且直接把动画值绑到样式上可能不会生效,得配合useAnimatedStyle来处理。给你调整了一套适配新版本的代码:import { Animated } from "react-native"; import { useSharedValue, useAnimatedStyle, withTiming } from "react-native-reanimated"; import { useEffect } from "react"; const CookingView = (props) => { // 用useSharedValue创建动画共享值 const cookAnim = useSharedValue(0); useEffect(() => { // 用withTiming实现定时动画 cookAnim.value = withTiming(1, { duration: 10000, }); }, []); // 用useAnimatedStyle创建动画样式 const animatedStyle = useAnimatedStyle(() => { return { opacity: cookAnim.value, }; }); return ( <Animated.View style={{ ...props.style, ...animatedStyle }}> {props.children} </Animated.View> ); }; export default CookingView;这样写不仅符合新版本的规范,动画性能也会更好,因为是用原生线程驱动的。
总的来说,你就是找错了API的归属库,调整一下导入和依赖,问题就能解决啦!
内容来源于stack exchange
相关产品推荐
相关产品推荐

