为什么你的Pressto动画不动了worklet指令与eslint-plugin-pressto避坑指南【免费下载链接】presstoYour React Native app deserves better tap interactions.项目地址: https://gitcode.com/gh_mirrors/pre/presstoPressto是一个专为 React Native 打造的点击交互动画组件库它用运行在 UI 主线程上的动画 Pressable 组件替代TouchableOpacity基于 react-native-reanimated 实现 60fps 的丝滑按压效果。但新手最常遇到的翻车现场就是动画突然不动了按钮变成木头人。90% 的情况下罪魁祸首是一个被遗忘的worklet指令。本文带你彻底搞懂这个坑并用eslint-plugin-pressto在开发阶段自动拦截它。 先搞懂worklet 指令是什么Pressto 的动画之所以流畅是因为动画函数运行在UI 线程UI thread而不是 JS 线程。Reanimated 的机制是只要函数体里带有worklet指令它就会被搬运到 UI 线程执行。const PressableRotate createAnimatedPressable((progress) { worklet; // ← 就靠这一行 return { transform: [{ rotate: ${progress * 45}deg }], }; });没有这一行动画函数就跑在了 JS 线程上表现就是不报错、不警告动画纹丝不动。这也是它比直接崩溃更坑的地方——你以为代码没问题其实只是跑错了线程。库内置的组件都帮你写好了这行指令例如缩放动画的实现见src/pressables/custom/scale.ts、透明度动画见src/pressables/custom/opacity.ts源码里第一行永远是worklet;。️ 你的动画不动了对照这 3 个经典踩坑姿势坑 1忘记写 worklet 指令// ❌ 错误缺少 worklet动画不运行 const AnimatedButton createAnimatedPressable(() { return { opacity: withSpring(1) }; }); // ✅ 正确第一行就是 worklet const AnimatedButton createAnimatedPressable(() { worklet; return { opacity: withSpring(1) }; });⚠️ 关键细节worklet必须是函数体的第一条语句放中间或末尾都无效。坑 2箭头函数隐式返回语法上就无法写指令// ❌ 错误隐式返回根本没有函数体写不进 worklet const AnimatedButton createAnimatedPressable(() ({ opacity: withSpring(1), }));这种写法再优雅也不行必须改成带花括块的显式return。坑 3空函数体// ❌ 错误空函数体同样会被拦截 const AnimatedButton createAnimatedPressable(() {});️ 快速上手用 eslint-plugin-pressto 自动拦截与其靠肉眼 review不如交给 ESLint。eslint-plugin-pressto提供了一条规则pressto/require-worklet-directive只要给createAnimatedPressable传入的函数缺少worklet指令就会直接报错Missing worklet directive in createAnimatedPressable function. Add worklet; as the first statement in the function body.安装npm install --save-dev eslint-plugin-pressto配置ESLint Flat Configeslint.config.jsconst presstoPlugin require(eslint-plugin-pressto); module.exports [ { plugins: { pressto: presstoPlugin }, rules: { pressto/require-worklet-directive: error, }, }, ];传统配置.eslintrc.jsmodule.exports { plugins: [pressto], rules: { pressto/require-worklet-directive: error, }, }; 规则是怎么判定的插件的规则实现位于eslint-plugin-pressto/rules/require-worklet-directive.js它会对每个createAnimatedPressable调用的第一个参数做三件事检查项结果箭头函数隐式返回无花括块❌ 报错空函数体❌ 报错第一条语句不是worklet字面量❌ 报错第一条语句为worklet;✅ 通过箭头函数和传统function表达式都能正确识别你不用纠结函数写法。 新手自查清单✅ 自定义动画函数第一行是worklet;✅ 没有用隐式返回的箭头函数✅ 项目已启用pressto/require-worklet-directive规则✅ 只改样式逻辑不要乱动指令位置 写在最后一行worklet指令就是 Pressto 动画能否在主线程飞奔起来的开关。记住口诀自定义动画第一行必写 worklet。再配上一个 ESLint 规则这个坑以后就彻底消失了。快去给你的按钮加上丝滑的 60fps 点击动画吧【免费下载链接】presstoYour React Native app deserves better tap interactions.项目地址: https://gitcode.com/gh_mirrors/pre/pressto创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考