美文网首页
react-native-reanimated系列(二)

react-native-reanimated系列(二)

作者: 十豆三撇 | 来源:发表于2021-03-24 16:21 被阅读0次

react-native-reanimated系列(一)

Worklets介绍

在Reanimated2中,通过生成一个辅助JS上下文来运行JavaScript函数。在函数体的第一行添加"worklet"指令即可。

function someWorklet(greeting) {
  'worklet';
  console.log("Hey I'm running on the UI thread");
}

每个worklet函数既可以在React Native线程上运行,也可以在UI线程上使用runOnUI执行它。从调用者的角度来看,UI执行是异步的。当你传递参数时,它们将被复制到UI JS上下文中。

function someWorklet(greeting) {
  'worklet';
  console.log(greeting, 'From the UI thread');
}

function onPress() {
  runOnUI(someWorklet)('Howdy');
}

除了参数之外,函数还会捕获定义它们的上下文。因此在worklet函数内使用定义在外部的变量时,它随参数一起被复制,这样你就可以使用它。

const width = 135.5;

function otherWorklet() {
  'worklet';
  console.log('Captured width is', width);
}

worklet函数调用worklet函数时,它们将在UI线程上同步执行。

function returningWorklet() {
  'worklet';
  return "I'm back";
}

function someWorklet() {
  'worklet';
  let what = returningWorklet();
  console.log('On the UI thread, other worklet says', what);
}

这也适用于常规方法。事实上,console.log并不是在UI JS上下文中定义的,而是React Native JS上下文提供的一个方法的引用。因此,当我们在前面的示例中使用console.log时,它实际上是在React Native线程上执行的。

function callback(text) {
  console.log('Running on the RN thread', text);
}

function someWorklet() {
  'worklet';
  console.log("I'm on UI but can call methods from the RN thread");
  runOnJS(callback)('can pass arguments too');
}

使用钩子

在实践中,我们一般使用的是由Reanimated API中的某个钩子构造的worklets,例如useAnimatedStyle, useDerivedValue, useAnimatedGestureHandler等等。Reanimated库会自动检测到提供的方法是否是一个worklet函数,而不需要指定worklet指令。提供给该钩子的方法将被转换成一个worklet函数,并在UI线程上自动执行。

const style = useAnimatedStyle(() => {
  console.log("Running on the UI thread");
  return {
    opacity: 0.5
  };
});

相关文章

网友评论

      本文标题:react-native-reanimated系列(二)

      本文链接:https://www.haomeiwen.com/subject/jxlhhltx.html