global.__reanimatedWorkletInit 不是函数。反应本机动画 v2

global.__reanimatedWorkletInit is not a function. react-native-animated v2

我使用 'worklet';runOnUI() 然后得到下面的错误。

因为我用'worklet';我加了import 'react-native-reanimated'

因为我也用runOnUI我加了import {runOnUI} from 'react-native-animated'

错误:

ERROR  TypeError: global.__reanimatedWorkletInit is not a function. (In 'global.__reanimatedWorkletInit(_f)', 'global.__reanimatedWorkletInit' is undefined)
 ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
      This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
 ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
      This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

简答:

除了 runOnUI 还从 react-native-reanimated 导入和使用其他内容,例如还添加 useSharedValue:

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

并使用共享值:

const sharedVal = useSharedValue(0);

现在错误将消失。


长答案(我是如何找到解决方案的):

起初我在尝试创建小部件时遇到错误(global.__reanimatedWorkletInit is not a function.):

import React from 'react';
import { Text } from 'react-native';

const Example = () => {
  const someWorklet = () => {
    'worklet';
    console.log("Hey I'm running on the UI thread");
  };

  return (<Text>Example</Text>);
};

export default Example;

添加 import 'react-native-reanimated'; 帮助我摆脱了错误。

然后我想运行someWorklet。所以我添加了一个 runOnJSrunOnUI 得到了相同的结果)调用。我的组件现在返回:

<View>
  <Text>Worklet: {runOnUI(someWorklet)()}</Text>
</View>

我通过 import { runOnUI } from 'react-native-reanimated';.

导入了它

现在又出现了同样的错误。

只有在我也导入并调用 useSharedValue 之后,一切都按预期进行。这是我的组件代码,它不再抛出错误:

import React from 'react';
import { View, Text } from 'react-native';
import { useSharedValue, runOnJS } from 'react-native-reanimated';

const Example = () => {
  const someWorklet = () => {
    'worklet';
    console.log("Hey I'm running on the UI thread");
    return 'World';
  };

  const sharedVal = useSharedValue(0);

  return (
    <View>
      <Text>Hello, {runOnJS(someWorklet)()}</Text>
    </View>
  );
};

export default Example;

只需在App.tsx和index.js

中添加这两行
1)import "react-native-reanimated"
2)global.__reanimatedWorkletInit = () => {}