You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native Web中实现共享元素转场动画?

解决方案

一、现有react-navigation-shared-element库修复方案

无动画问题核心有三个原因:web端编译配置不完整、react-navigation v6默认关闭了web端的栈过渡动画、缺少必要的动画依赖,可按以下步骤修复:

1. 补全依赖

首先安装动画核心依赖:

npm install react-native-reanimated@~2.14.4

修改babel配置的plugins数组,新增reanimated编译插件:

plugins: ['react-native-web', 'react-native-reanimated/plugin'],

2. 修改webpack babel编译配置

原有配置仅编译src目录代码,需要将共享元素相关库加入编译范围,修改babelLoaderConfiguration的include字段:

include: [
  path.resolve(appDirectory, 'src'),
  // 新增以下两行
  path.resolve(appDirectory, 'node_modules/react-native-shared-element'),
  path.resolve(appDirectory, 'node_modules/react-navigation-shared-element'),
],

3. 调整导航配置开启web端动画

修改Stack.Navigator配置,强制开启过渡动画:

<Stack.Navigator
  screenOptions={{
    animationEnabled: true,
    // 统一两端动画效果
    animation: 'slide_from_right',
  }}
>

同时简化B页面的sharedElements配置先做测试:

sharedElements={() => ['shared']}

调整后重新编译即可看到共享元素过渡效果。

二、跨端兼容替代方案(兼容性更稳定)

如果上述方案仍存在兼容性问题,可以采用分端底层封装、上层统一调用的方案,无需修改业务代码结构:

技术选型

  • 移动端:继续使用现有react-navigation-shared-element实现,兼容原有逻辑
  • Web端:使用framer-motion的共享布局动画实现,性能和效果更适配浏览器环境

封装实现

  1. 新建SharedElement.native.js,移动端实现:
import { SharedElement } from 'react-navigation-shared-element';
export default SharedElement;
  1. 新建SharedElement.web.js,Web端实现:
import { motion } from 'framer-motion';
export default function SharedElement({ id, children }) {
  return <motion.div layoutId={id}>{children}</motion.div>;
}
  1. Web端路由外层包裹动画容器,修改App.js的web版:
import { AnimatePresence } from 'framer-motion';
// 其余导入保持不变

export default function App() {
  return (
    <NavigationContainer>
      <AnimatePresence mode="wait">
        <Stack.Navigator
          screenOptions={{
            animationEnabled: false, // 关闭原有栈动画,用framer-motion替代
          }}
        >
          {/* 原有Screen配置保持不变 */}
        </Stack.Navigator>
      </AnimatePresence>
    </NavigationContainer>
  );
}

上层业务代码无需任何修改,共享元素id配置保持和原有逻辑一致即可同时支持两端效果。

内容的提问来源于stack exchange,提问作者Kacperito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:06:03