preface

Since I’m in the infrastructure group now, I don’t have a UI framework for writing projects, so I basically have to encapsulate them myself. So I have to write one

Wheel – cast graph component, thought this is not a matter of minutes. Just write…

The first edition

Ideas: ul Li structure, combined with JS timer to achieve the rotation of animation, dry dry…

Seamless sliding principle: red 1, 3 are cloned transition elements. Index from 34As soon as the animation ends, slide the pointer to 1 for seamless rotation.

Below the JS animation pseudocode

Carousel.tsx


interface Props {
    children: React.ReactNode
}
const PERCENTAGE = 100; / / percentage

const Carousel = (props: Props) = > {

  const [left, setLeft] = useState(0)
  let  tempLeft = useRef(left);
  
  const transform = (target) = > {
      let timer = setInterval(() = > {
          if (Math.abs(tempLeft.current - target) <= 1 ) {
            clearInterval(timer)
            tempLeft.current = target;
            setLeft(target);
            
            if (target/PERCENTAGE >= len + 1) {
                // Now we have slid to the last element we cloned
                setIndex(1). // Just slide to the first slide to make it seamless.
                setLeft(100)
                return}}letStep = (target-templeft.current) /10;
          step = step > 0 ? Math.ceil(step) : Math.floor(step);
          tempLeft.current = tempLeft.current + step;
          setLeft(() = > tempLeft.current);
      }, 20)}return (
        <div className="carousel">
            <ul 
                className="carousel__container"
                style={{
                  left: `-The ${left} % `,width: (len + 2) * PERCENTAGE+ "%}}" >{children[len-1]} // Clone the last element to the first {children} {children[0]} // clone the first element to the last element</ul>
            
        </div>)}Copy the code

Basically seamless rotation is achieved, but also need to add a logo is animation, to prevent users from clicking too fast, abnormal.

  • There are also several problems with this implementation, such as changing state frequently and rendering components too many times. So we can consider using CSS for animation.
  • Use timers to complete animations, and indescribable things may happen…

The second edition

CSS animations



const transform = (target) = > {

      timeoutId.current && clearTimeout(timeoutId.current);
      needAnimate.current = true;
      setLeft(target);

      if (target / 100 >= len + 1) {
        // Let's scroll down to the actual first element
        timeoutId.current = setTimeout(() = > {
          needAnimate.current = false;
          setLeft(100);
          setIndex(1);
        }, 350);
      }

    
}



    <ul
        style={{
            left: ` -${index * 100}% `.width: (len + 2) * 100 + The '%'.transition: needAnimate.current ? "All 0.3 s" : "none"}} >... </ul>Copy the code

These are the two ways to write, it is recommended to use CSS animation is better