经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » React » 查看文章
React跨路由组件动画
来源:cnblogs  作者:袋鼠云数栈前端  时间:2023/10/11 16:11:25  对本文有异议

我们是袋鼠云数栈 UED 团队,致力于打造优秀的一站式数据中台产品。我们始终保持工匠精神,探索前端道路,为社区积累并传播经验价值。

本文作者:佳岚

回顾传统React动画

对于普通的 React 动画,我们大多使用官方推荐的 react-transition-group,其提供了四个基本组件 Transition、CSSTransition、SwitchTransition、TransitionGroup

Transition

Transition 组件允许您使用简单的声明式 API 来描述组件的状态变化,默认情况下,Transition 组件不会改变它呈现的组件的行为,它只跟踪组件的“进入”和“退出”状态,我们需要做的是赋予这些状态意义。

其一共提供了四种状态,当组件感知到 in prop 变化时就会进行相应的状态过渡

  • 'entering'
  • 'entered'
  • 'exiting'
  • 'exited'
  1. const defaultStyle = {
  2. transition: `opacity ${duration}ms ease-in-out`,
  3. opacity: 0,
  4. }
  5. const transitionStyles = {
  6. entering: { opacity: 1 },
  7. entered: { opacity: 1 },
  8. exiting: { opacity: 0 },
  9. exited: { opacity: 0 },
  10. };
  11. const Fade = ({ in: inProp }) => (
  12. <Transition in={inProp} timeout={duration}>
  13. {state => (
  14. <div style={{
  15. ...defaultStyle,
  16. ...transitionStyles[state]
  17. }}>
  18. I'm a fade Transition!
  19. </div>
  20. )}
  21. </Transition>
  22. );

CSSTransition

此组件主要用来做 CSS 样式过渡,它能够在组件各个状态变化的时候给我们要过渡的标签添加上不同的类名。所以参数和平时的 className 不同,参数为:classNames

  1. <CSSTransition
  2. in={inProp}
  3. timeout={300}
  4. classNames="fade"
  5. unmountOnExit
  6. >
  7. <div className="star">?</div>
  8. </CSSTransition>
  9. // 定义过渡样式类
  10. .fade-enter {
  11. opacity: 0;
  12. }
  13. .fade-enter-active {
  14. opacity: 1;
  15. transition: opacity 200ms;
  16. }
  17. .fade-exit {
  18. opacity: 1;
  19. }
  20. .fade-exit-active {
  21. opacity: 0;
  22. transition: opacity 200ms;
  23. }

SwitchTransition

SwitchTransition 用来做组件切换时的过渡,其会缓存传入的 children,并在过渡结束后渲染新的 children

  1. function App() {
  2. const [state, setState] = useState(false);
  3. return (
  4. <SwitchTransition>
  5. <CSSTransition
  6. key={state ? "Goodbye, world!" : "Hello, world!"}
  7. classNames='fade'
  8. >
  9. <button onClick={() => setState(state => !state)}>
  10. {state ? "Goodbye, world!" : "Hello, world!"}
  11. </button>
  12. </CSSTransition>
  13. </SwitchTransition>
  14. );
  15. }

TransitionGroup

如果有一组 CSSTransition 需要我们去过渡,那么我们需要管理每一个 CSSTransition 的 in 状态,这样会很麻烦。

TransitionGroup 可以帮我们管理一组 Transition 或 CSSTransition 组件,为此我们不再需要给 Transition 组件传入 in 属性来标识过渡状态,转用 key 属性来代替 in

  1. <TransitionGroup>
  2. {
  3. this.state.list.map((item, index) => {
  4. return (
  5. <CSSTransition
  6. key = {item.id}
  7. timeout = {1000}
  8. classNames = 'fade'
  9. unmountOnExit
  10. >
  11. <TodoItem />
  12. </CSSTransition>
  13. )
  14. }
  15. }
  16. </TransitionGroup>

TransitionGroup 会监测其 children 的变化,将新的 children 与原有的 children 使用 key 进行比较,就能得出哪些 children 是新增的与删除的,从而为他们注入进场动画或离场动画。

file

FLIP 动画

FLIP 是什么?

FLIPFirstLastInvertPlay四个单词首字母的缩写

First, 元素过渡前开始位置信息

Last:执行一段代码,使元素位置发生变化,记录最后状态的位置等信息.

Invert:根据 First 和 Last 的位置信息,计算出位置差值,使用 transform: translate(x,y) 将元素移动到First的位置。

Play:  给元素加上 transition 过渡属性,再讲 transform 置为 none,这时候因为 transition 的存在,开始播放丝滑的动画。

Flip 动画可以看成是一种编写动画的范式,方法论,对于开始或结束状态未知的复杂动画,可以使用 Flip 快速实现

位置过渡效果

file

代码实现:

  1. const container = document.querySelector('.flip-container');
  2. const btnAdd = document.querySelector('#add-btn')
  3. const btnDelete = document.querySelector('#delete-btn')
  4. let rectList = []
  5. function addItem() {
  6. const el = document.createElement('div')
  7. el.className = 'flip-item'
  8. el.innerText = rectList.length + 1;
  9. el.style.width = (Math.random() * 300 + 100) + 'px'
  10. // 加入新元素前重新记录起始位置信息
  11. recordFirst();
  12. // 加入新元素
  13. container.prepend(el)
  14. rectList.unshift({
  15. top: undefined,
  16. left: undefined
  17. })
  18. // 触发FLIP
  19. update()
  20. }
  21. function removeItem() {
  22. const children = container.children;
  23. if (children.length > 0) {
  24. recordFirst();
  25. container.removeChild(children[0])
  26. rectList.shift()
  27. update()
  28. }
  29. }
  30. // 记录位置
  31. function recordFirst() {
  32. const items = container.children;
  33. for (let i = 0; i < items.length; i++) {
  34. const rect = items[i].getBoundingClientRect();
  35. rectList[i] = {
  36. left: rect.left,
  37. top: rect.top
  38. }
  39. }
  40. }
  41. function update() {
  42. const items = container.children;
  43. for (let i = 0; i < items.length; i++) {
  44. // Last
  45. const rect = items[i].getBoundingClientRect();
  46. if (rectList[i].left !== undefined) {
  47. // Invert
  48. const transformX = rectList[i].left - rect.left;
  49. const transformY = rectList[i].top - rect.top;
  50. items[i].style.transform = `translate(${transformX}px, ${transformY}px)`
  51. items[i].style.transition = "none"
  52. // Play
  53. requestAnimationFrame(() => {
  54. items[i].style.transform = `none`
  55. items[i].style.transition = "all .5s"
  56. })
  57. }
  58. }
  59. }
  60. btnAdd.addEventListener('click', () => {
  61. addItem()
  62. })
  63. btnDelete.addEventListener('click', () => {
  64. removeItem()
  65. })

使用 flip 实现的动画 demo

乱序动画:

file

缩放动画:

React跨路由组件动画

在 React 中路由之前的切换动画可以使用 react-transition-group 来实现,但对于不同路由上的组件如何做到动画过渡是个很大的难题,目前社区中也没有一个成熟的方案。

使用flip来实现

在路由 A 中组件的大小与位置状态可以当成 First, 在路由 B 中组件的大小与位置状态可以当成 Last

从路由 A 切换至路由B时,向 B 页面传递 First 状态,B 页面中需要过渡的组件再进行 Flip 动画。

为此我们可以抽象出一个组件来帮我们实现 Flip 动画,并且能够在切换路由时保存组件的状态。

对需要进行过渡的组件进行包裹, 使用相同的 flipId 来标识他们需要在不同的路由中过渡。

  1. <FlipRouteAnimate className="about-profile" flipId="avatar" animateStyle={{ borderRadius: "15px" }}>
  2. <img src={require("./touxiang.jpg")} alt="" />
  3. </FlipRouteAnimate>

完整代码:

  1. import React, { createRef } from "react";
  2. import withRouter from "./utils/withRouter";
  3. class FlipRouteAnimate extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.flipRef = createRef();
  7. }
  8. // 用来存放所有实例的rect
  9. static flipRectMap = new Map();
  10. componentDidMount() {
  11. const {
  12. flipId,
  13. location: { pathname },
  14. animateStyle: lastAnimateStyle,
  15. } = this.props;
  16. const lastEl = this.flipRef.current;
  17. // 没有上一个路由中组件的rect,说明不用进行动画过渡
  18. if (!FlipRouteAnimate.flipRectMap.has(flipId) || flipId === undefined) return;
  19. // 读取缓存的rect
  20. const first = FlipRouteAnimate.flipRectMap.get(flipId);
  21. if (first.route === pathname) return;
  22. // 开始FLIP动画
  23. const firstRect = first.rect;
  24. const lastRect = lastEl.getBoundingClientRect();
  25. const transformOffsetX = firstRect.left - lastRect.left;
  26. const transformOffsetY = firstRect.top - lastRect.top;
  27. const scaleRatioX = firstRect.width / lastRect.width;
  28. const scaleRatioY = firstRect.height / lastRect.height;
  29. lastEl.style.transform = `translate(${transformOffsetX}px, ${transformOffsetY}px) scale(${scaleRatioX}, ${scaleRatioY})`;
  30. lastEl.style.transformOrigin = "left top";
  31. for (const styleName in first.animateStyle) {
  32. lastEl.style[styleName] = first.animateStyle[styleName];
  33. }
  34. setTimeout(() => {
  35. lastEl.style.transition = "all 2s";
  36. lastEl.style.transform = `translate(0, 0) scale(1)`;
  37. // 可能有其他属性也需要过渡
  38. for (const styleName in lastAnimateStyle) {
  39. lastEl.style[styleName] = lastAnimateStyle[styleName];
  40. }
  41. }, 0);
  42. }
  43. componentWillUnmount() {
  44. const {
  45. flipId,
  46. location: { pathname },
  47. animateStyle = {},
  48. } = this.props;
  49. const el = this.flipRef.current;
  50. // 组件卸载时保存自己的位置等状态
  51. const rect = el.getBoundingClientRect();
  52. FlipRouteAnimate.flipRectMap.set(flipId, {
  53. // 当前路由路径
  54. route: pathname,
  55. // 组件的大小位置
  56. rect: rect,
  57. // 其他需要过渡的样式
  58. animateStyle,
  59. });
  60. }
  61. render() {
  62. return (
  63. <div
  64. className={this.props.className}
  65. style={{ display: "inline-block", ...this.props.style, ...this.props.animateStyle }}
  66. ref={this.flipRef}
  67. >
  68. {this.props.children}
  69. </div>
  70. );
  71. }
  72. }

实现效果:

file

共享组件的方式实现

要想在不同的路由共用同一个组件实例,并不现实,树形的 Dom 树并不允许我们这么做。

file

我们可以换个思路,把组件提取到路由容器的外部,然后通过某种方式将该组件与路由页面相关联。

file

我们将 Float 组件提升至根组件,然后在每个路由中使用 Proxy 组件进行占位,当路由切换时,每个 Proxy 将其位置信息与其他 props 传递给 Float 组件,Float 组件再根据接收到的状态信息,将自己移动到对应位置。

我们先封装一个 Proxy 组件,  使用 PubSub 发布元信息。

  1. // FloatProxy.tsx
  2. const FloatProxy: React.FC<any> = (props: any) => {
  3. const el = useRef();
  4. // 保存代理元素引用,方便获取元素的位置信息
  5. useEffect(() => {
  6. PubSub.publish("proxyElChange", el);
  7. return () => {
  8. PubSub.publish("proxyElChange", null);
  9. }
  10. }, []);
  11. useEffect(() => {
  12. PubSub.publish("metadataChange", props);
  13. }, [props]);
  14. const computedStyle = useMemo(() => {
  15. const propStyle = props.style || {};
  16. return {
  17. border: "dashed 1px #888",
  18. transition: "all .2s ease-in",
  19. ...propStyle,
  20. };
  21. }, [props.style]);
  22. return <div {...props} style={computedStyle} ref={el}></div>;
  23. };

在路由中使用, 将样式信息进行传递

  1. class Bar extends React.Component {
  2. render() {
  3. return (
  4. <div className="container">
  5. <p>bar</p>
  6. <div style={{ marginTop: "140px" }}>
  7. <FloatProxy style={{ width: 120, height: 120, borderRadius: 15, overflow: "hidden" }} />
  8. </div>
  9. </div>
  10. );
  11. }
  12. }

创建全局变量用于保存代理信息

  1. // floatData.ts
  2. type ProxyElType = {
  3. current: HTMLElement | null;
  4. };
  5. type MetaType = {
  6. attrs: any;
  7. props: any;
  8. };
  9. export const metadata: MetaType = {
  10. attrs: {
  11. hideComponent: true,
  12. left: 0,
  13. top: 0
  14. },
  15. props: {},
  16. };
  17. export const proxyEl: ProxyElType = {
  18. current: null,
  19. };

创建一个FloatContainer容器组件,用于监听代理数据的变化,  数据变动时驱动组件进行移动

  1. import { metadata, proxyEl } from "./floatData";
  2. class FloatContainer extends React.Component<any, any> {
  3. componentDidMount() {
  4. // 将代理组件上的props绑定到Float组件上
  5. PubSub.subscribe("metadataChange", (msg, props) => {
  6. metadata.props = props;
  7. this.forceUpdate();
  8. });
  9. // 切换路由后代理元素改变,保存代理元素的位置信息
  10. PubSub.subscribe("proxyElChange", (msg, el) => {
  11. if (!el) {
  12. metadata.attrs.hideComponent = true;
  13. // 在下一次tick再更新dom
  14. setTimeout(() => {
  15. this.forceUpdate();
  16. }, 0);
  17. return;
  18. } else {
  19. metadata.attrs.hideComponent = false;
  20. }
  21. proxyEl.current = el.current;
  22. const rect = proxyEl.current?.getBoundingClientRect()!;
  23. metadata.attrs.left = rect.left;
  24. metadata.attrs.top = rect.top
  25. this.forceUpdate();
  26. });
  27. }
  28. render() {
  29. const { timeout = 500 } = this.props;
  30. const wrapperStyle: React.CSSProperties = {
  31. position: "fixed",
  32. left: metadata.attrs.left,
  33. top: metadata.attrs.top,
  34. transition: `all ${timeout}ms ease-in`,
  35. // 当前路由未注册Proxy时进行隐藏
  36. display: metadata.attrs.hideComponent ? "none" : "block",
  37. };
  38. const propStyle = metadata.props.style || {};
  39. // 注入过渡样式属性
  40. const computedProps = {
  41. ...metadata.props,
  42. style: {
  43. transition: `all ${timeout}ms ease-in`,
  44. ...propStyle,
  45. },
  46. };
  47. console.log(metadata.attrs.hideComponent)
  48. return <div className="float-element" style={wrapperStyle}>{this.props.render(computedProps)} </div>;
  49. }
  50. }

将组件提取到路由容器外部,并使用 FloatContainer 包裹

  1. function App() {
  2. return (
  3. <BrowserRouter>
  4. <div className="App">
  5. <NavLink to={"/"}>/foo</NavLink>
  6. <NavLink to={"/bar"}>/bar</NavLink>
  7. <NavLink to={"/baz"}>/baz</NavLink>
  8. <FloatContainer render={(attrs: any) => <MyImage {...attrs}/>}></FloatContainer>
  9. <Routes>
  10. <Route path="/" element={<Foo />}></Route>
  11. <Route path="/bar" element={<Bar />}></Route>
  12. <Route path="/baz" element={<Baz />}></Route>
  13. </Routes>
  14. </div>
  15. </BrowserRouter>
  16. );
  17. }

实现效果:

file

目前我们实现了一个单例的组件,我们将组件改造一下,让其可以被复用

首先我们将元数据更改为一个元数据 map,以 layoutId 为键,元数据为值

  1. // floatData.tsx
  2. type ProxyElType = {
  3. current: HTMLElement | null;
  4. };
  5. type MetaType = {
  6. attrs: {
  7. hideComponent: boolean,
  8. left: number,
  9. top: number
  10. };
  11. props: any;
  12. };
  13. type floatType = {
  14. metadata: MetaType,
  15. proxyEl: ProxyElType
  16. }
  17. export const metadata: MetaType = {
  18. attrs: {
  19. hideComponent: true,
  20. left: 0,
  21. top: 0
  22. },
  23. props: {},
  24. };
  25. export const proxyEl: ProxyElType = {
  26. current: null,
  27. };
  28. export const floatMap = new Map<string, floatType>()

在代理组件中传递layoutId 来通知注册了相同layoutId的floatContainer做出相应变更

  1. // FloatProxy.tsx
  2. // 保存代理元素引用,方便获取元素的位置信息
  3. useEffect(() => {
  4. const float = floatMap.get(props.layoutId);
  5. if (float) {
  6. float.proxyEl.current = el.current;
  7. } else {
  8. floatMap.set(props.layoutId, {
  9. metadata: {
  10. attrs: {
  11. hideComponent: true,
  12. left: 0,
  13. top: 0,
  14. },
  15. props: {},
  16. },
  17. proxyEl: {
  18. current: el.current,
  19. },
  20. });
  21. }
  22. PubSub.publish("proxyElChange", props.layoutId);
  23. return () => {
  24. if (float) {
  25. float.proxyEl.current = null
  26. PubSub.publish("proxyElChange", props.layoutId);
  27. }
  28. };
  29. }, []);
  30. // 在路由中使用
  31. <FloatProxy layoutId='layout1' style={{ width: 200, height: 200 }} />

在FloatContainer组件上也加上layoutId来标识同一组

  1. // FloatContainer.tsx
  2. // 监听到自己同组的Proxy发送消息时进行rerender
  3. PubSub.subscribe("metadataChange", (msg, layoutId) => {
  4. if (layoutId === this.props.layoutId) {
  5. this.forceUpdate();
  6. }
  7. });
  8. // 页面中使用
  9. <FloatContainer layoutId='layout1' render={(attrs: any) => <MyImage imgSrc={img} {...attrs} />}></FloatContainer>

实现多组过渡的效果

file

最后

欢迎关注【袋鼠云数栈UED团队】~
袋鼠云数栈UED团队持续为广大开发者分享技术成果,相继参与开源了欢迎star

原文链接:https://www.cnblogs.com/dtux/p/17756569.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号