FLIP is an acronym for First, Last, Invert and Play

  • First: Retain the state before the change
  • Last: Records the status after the change
  • 1. Restore to first state by first and last calculations
  • Play: Perform animation to achieve the transition from first to last

Image to flip

import "web-animations-js"
import React, { useState, useEffect, useLayoutEffect, useRef } from "react";
import styled from "styled-components";

const Container = styled.div`
  display: flex;
  flex-wrap: wrap;
  column-count: 4;
  margin: auto;
  width: 800px;
`;
const ImgWrap = styled.div`
  width: 25%;
  padding: 8px;
  box-sizing: border-box;
`;
const Img = styled.img`
  width: 100%;
  height: 200px;
  border-radius: 8px;
  object-fit: cover;
`;

export default function() {// root const root = useRef(); // keep the previous state const prev = useRef(null); const [imgs,setImgs] = useState([
    "https://pic3.zhimg.com/v2-89735fee10045d51693f1f74369aaa46_r.jpg"."https://pic1.zhimg.com/v2-ca51a8ce18f507b2502c4d495a217fa0_r.jpg"."https://pic1.zhimg.com/v2-c90799771ed8469608f326698113e34c_r.jpg"."https://pic1.zhimg.com/v2-8d3dd83f3a419964687a028de653f8d8_r.jpg"."https://pic1.zhimg.com/v2-09eefac19ac282684f60a202aa9abb2c_r.jpg"."https://pic3.zhimg.com/v2-a7340ebca1f7a4f65190583b4ab3a482_r.jpg"."https://pic2.zhimg.com/v2-37860484a1a73257178e95267c7db641_r.jpg"."https://pic2.zhimg.com/v2-7fc30291c807d07d2d26c5a8ffdd3b89_r.jpg",]); useLayoutEffect(() => {ifPrev. current = array. from(root.current. Children).map((dom) => {const rect = dom.getBoundingClientRect();return { dom, pos: { left: rect.left, top: rect.top } };
      });
    } else({{prev. Current. The map (dom, pos}) = > {/ / to get a new state const dom. The rect = getBoundingClientRect (); // invent restore to initial state dom.style = 'transform: translate(${pos.left - rect.left}px, ${ pos.top - rect.top }px)`; Dom. Animate ([{transform: 'translate' (${pos.left - rect.left}px, ${
                pos.top - rect.top
              }px)`,
            },
            {
              transform: "Translate (0, 0)",
            },
          ],
          {
            duration: 300,
            easing: "Cubic - the bezier (,0,0.32 0, 1)",
            fill: "forwards"}); }); / / save state before the prev. Current = Array. The from (root. Current. Children.) the map ((dom) = > {const the rect = dom. GetBoundingClientRect ();return { dom, pos: { left: rect.left, top: rect.top } };
      });
    }
  }, [imgs]);
  return(< Container ref = {root} > {imgs. The map ((img) = > (< ImgWrap key = {img} onClick = {() = > {/ / to disrupt an arraysetImgs ((Imgs) = > [Imgs s sort (() = > (Math) random () > 0.5? 1:1)),]); }} > <Img src={img} /> </ImgWrap> ))} </Container> ); }Copy the code