umi 如何实现标签页切换和路由动效

全局路由

在umi项目的src中创建layouts,src/layouts/index.js中编写一个react组件。

组件默认接收一个props属性为childrenchildren将会默认渲染src/page/index.js下也就是umi的默认进入页,路由切换时等于是切换children部分。

剩下的部分可以全局渲染,因此可以把标签渲染在底部全局,children放在上方,就达到了点击下方标签,切换路由的效果。

示例

我示例使用的是antd-mobile v5.0.0-rc.3react-transition-group,在umi项目中需要额外安装。

yarn add react-transition-group
yarn add antd-mobile@v5.0.0-rc.3

src/layouts/index.js代码

  1. 我想要的效果是标签页的切换都是用replace实现,当检测history.action === 'REPLACE'时,则根据标签页的前后顺序决定向左还是向右切换动画。
  2. history.action === 'PUSH'或者'POP'时,后续将会PUSH进入二级页面,就是前进,点击浏览器后退就是POP后退
import styles from './index.less';
import { TabBar } from 'antd-mobile/2x';
import router from 'umi/router';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import withRouter from 'umi/withRouter';

import React, { useState } from 'react';

import home1 from '@/assets/home1.png';
import home2 from '@/assets/home2.png';
import update1 from '@/assets/update1.png';
import update2 from '@/assets/update2.png';
import collect1 from '@/assets/collect1.png';
import collect2 from '@/assets/collect2.png';
import my1 from '@/assets/my1.png';
import my2 from '@/assets/my2.png';

export default withRouter(({ location, children, history }) => {
  // 根据前进还是后退显示不同的转场动画效果
  const ANIMATION_MAP = {
    PUSH: 'forward',
    POP: 'back',
  };

  // 路由跳转时执行
  const checkrouter = () => {
    const { state = {} } = location;
    //beforepath 跳转前路由,只有在四个标签页跳转时有传递
    const { beforepath } = state;
    //curpath 当前路由
    const curpath = history.location.pathname;
    // 标签页路由集合
    const indexRouter = ['/', '/update', '/collect', '/my'];
    // 判断是不是标签页跳转
    const flag = history.action === 'REPLACE';
    // 判断标签页跳转前后顺序
    const before = indexRouter.findIndex(cur => cur === beforepath);
    const after = indexRouter.findIndex(cur => cur === curpath);
    const change = before < after ? 'PUSH' : 'POP';
    // 如果当前路由不是标签,说明跳去了二级页面,应该隐藏标签
    sethide(after === -1);
    // 设置转场动画效果
    return ANIMATION_MAP[flag ? change : history.action];
  };

  // 判断标签页是否隐藏
  const [hide, sethide] = useState(false);

  const tabs = [
    {
      key: '/',
      title: '首页',
      icon: <img src={home1} className={styles.iconImg} alt="首页" />,
      selectedIcon: <img src={home2} className={styles.iconImg} alt="首页" />,
    },
    {
      key: '/update',
      title: '更新',
      icon: <img src={update1} className={styles.iconImg} alt="更新" />,
      selectedIcon: <img src={update2} className={styles.iconImg} alt="更新" />,
    },
    {
      key: '/collect',
      title: '收藏',
      icon: <img src={collect1} className={styles.iconImg} alt="收藏" />,
      selectedIcon: <img src={collect2} className={styles.iconImg} alt="收藏" />,
    },
    {
      key: '/my',
      title: '我的',
      icon: <img src={my1} className={styles.iconImg} alt="我的" />,
      selectedIcon: <img src={my2} className={styles.iconImg} alt="我的" />,
    },
  ];

  return (
    <div
      style={{ display: 'flex', flexDirection: 'column', height: '100%', paddingBottom: '5rem' }}
    >
      <div style={{ flex: 1, display: 'flex', overflow: 'auto' }}>
        <TransitionGroup
          childFactory={child => React.cloneElement(child, { classNames: checkrouter() })}
        >
          <CSSTransition
            key={location.pathname}
            timeout={300}
            style={{
              position: 'fixed',
              height: '100%',
              width: '100%',
              top: '0',
              overflow: 'auto',
              // 隐藏标签时要把下方padding重置为0
              paddingBottom: hide ? '0rem' : '5rem',
            }}
          >
            <div>{children}</div>
          </CSSTransition>
        </TransitionGroup>
      </div>

      <div className={styles.normal} style={{ visibility: hide ? 'hidden' : 'unset' }}>
        <TabBar
          activeKey={location.pathname}
          onChange={beforepath =>
            // 标签跳转,使用replace,同时传递跳转前路由
            router.replace(beforepath, { beforepath: history.location.pathname })
          }
        >
          {tabs.map(item => (
            <TabBar.Item
              key={item.key}
              // 切换选中未选中图片
              icon={location.pathname === item.key ? item.selectedIcon : item.icon}
              title={item.title}
            />
          ))}
        </TabBar>
      </div>
    </div>
  );
});

样式代码

src/global.less

  1. 我是用rem加vw的方式做全局适配。因此你会看到我使用长度一般是rem/20这种奇怪的单位,1rem等于html的font-size100/750vw*20,则750rem/20就是100vw,就是一整个屏幕宽度,一般的ui设计图是750px,也就是只要把设计图上的数字使用rem/20单位就可以进行任何设备的适配了。
html,
body,
#root {
  height: 100%;
  font-family: '楷体';
}

html {
  font-size: 100/750vw*20;
}

body {
  margin: 0;
}

src/loyouts/index.less

  1. 前进和后退的动作在前半部分,后面是antd页标签的适配调整,可以适配大屏小屏任何设备。
:global {
  .forward-enter {
    opacity: 0;
    transform: translateX(100%);
  }

  .forward-enter-active {
    opacity: 1;
    transform: translateX(0);
    transition: all 300ms ease-in;
  }

  .forward-exit {
    opacity: 1;
    transform: translateX(0);
  }

  .forward-exit-active {
    opacity: 0;
    transform: translateX(-100%);
    transition: all 300ms ease-in;
  }

  .back-enter {
    opacity: 0;
    transform: translateX(-100%);
  }

  .back-enter-active {
    opacity: 1;
    transform: translateX(0);
    transition: all 300ms ease-in;
  }

  .back-exit {
    opacity: 1;
    transform: translateX(0);
  }

  .back-exit-active {
    opacity: 0;
    transform: translate(100%);
    transition: all 300ms ease-in;
  }
}


.normal {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 100rem/20;
  background-color: white;
  // border-top: 1rem/20 solid lightgray;
  box-shadow: 0 -1px 10px 1px rgba(0, 0, 0, 0.1);

  :global {
    .adm-tab-bar-item {
      height: 100rem/20;

      .adm-tab-bar-item-icon {
        height: 40rem/20;
        width: 40rem/20;
        margin: 0;
        font-size: initial;
      }

      .adm-tab-bar-item-title {
        font-size: 24rem/20;
        line-height: unset;
      }
    }

    .adm-tab-bar-item-active {
      color: #B9E2F6;
    }
  }
}

.iconImg {
  width: 40rem/20;
  height: $width;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
umi,可以使用插件`@umijs/plugin-persisted-state`来实现切换路由时缓存之前面的数据。该插件使用了`localStorage`来持久化存储数据,以便在切换面后能够重新加载。 以下是如何使用`@umijs/plugin-persisted-state`插件进行数据缓存的步骤: 1. 安装插件: ```shell npm install @umijs/plugin-persisted-state --save ``` 2. 在`.umirc.js`或`config/config.js`文件配置插件: ```javascript export default { plugins: [ ['@umijs/plugin-persisted-state', { storage: 'localStorage', // 存储方式,可选localStorage、sessionStorage、cookie,默认localStorage key: 'yourKey' // 存储的键名,默认为 "persistedState" }] ] } ``` 3. 在需要缓存数据的组件使用`usePersistedState`钩子来获取和设置缓存数据: ```javascript import { usePersistedState } from 'umi'; function MyComponent() { const [data, setData] = usePersistedState('yourKey', initialValue); // 使用data进行渲染和操作 // 使用setData更新data的值 return <div>{data}</div>; } ``` 在上述代码,`usePersistedState`钩子接收两个参数:键名和初始值。它会返回一个数组,第一个元素是缓存的数据,第二个元素是更新数据的函数。通过使用`usePersistedState`,你可以在切换路由后获取之前面的数据,并在组件使用它。 注意,`@umijs/plugin-persisted-state`插件默认使用`localStorage`来存储数据,如果需要使用其他存储方式,可以在配置进行设置。 希望以上内容对你有所帮助!如有任何疑问,请随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

在下月亮有何贵干

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值