使用 React Reanimated 3,如何修复“错误:只能在 UI 运行时直接从 `_value` 读取”?

She*_*ims 7 reactjs react-native react-native-reanimated

按照此处的React Native 重新启动文档,我有以下代码:

import Animated, { useSharedValue, useAnimatedStyle } from 'react-native-reanimated';

function WobbleExample(props) {
  const rotation = useSharedValue(0);

  const animatedStyle = useAnimatedStyle(() => {
    return {
      transform: [{ rotateZ: `${rotation.value}deg` }],
    };
  });

  return (
    <>
      <Animated.View style={[styles.box, animatedStyle]} />
      <Button
        title="wobble"
        onPress={() => {
          rotation.value = withRepeat(withTiming(10), 6, true)

        }}
      />
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

但我在我的 Metro 控制台中看到这个,应用程序崩溃了

Error: Reading from `_value` directly is only possible on the UI runtime

This error is located at:
    in AnimatedComponent (at createAnimatedComponent.js:264)
    ...
Run Code Online (Sandbox Code Playgroud)

非常感谢任何有关如何修复的建议!

小智 12

我也遇到了同样的问题,但就我而言,我是从react-native而不是react-native-reanimated导入Animated

import Animated from 'react-native-reanimated';
Run Code Online (Sandbox Code Playgroud)


Spa*_*hut 8

当尝试将动画样式传递给常规样式View而不是Animated.View.


小智 6

当使用 useAnimationStyle 和插值的共享值时,与我类似的问题。

const animatedStyles = useAnimatedStyle(() => {
    const Y = energyLevel?.value ?? 5.5;
    const bottomScreen = -height + heightOffset * 2;
    const topScreen = height - heightOffset * 2;
    const offsetY = interpolate(Y, [1, 10], [bottomScreen, topScreen]);
    return {
      transform: [{translateY: offsetY}],
    };
  });
Run Code Online (Sandbox Code Playgroud)

但问题是动画导入:

    import Animated from 'react-native-reanimated';
Run Code Online (Sandbox Code Playgroud)