React implements the snake effect component around the disk or square

1.Demand

I need to realize a square button with a dynamic effect like a snake around it. How to achieve it through react? The effect is as follows:

.........

There are more than 20 pictures in total, just like a greedy snake, they change every 100 milliseconds to achieve the effect of dynamic running. 

2. Realize

Write the function that needs to be implemented above into a component, and the page can directly call the component. The code is as follows: 

To introduce the code to the component page: 

import Roll from "../../components/Roll";
 
const Index = () => {
 
 return (
        <div class={style.main}>
            <div class={style.roll}>
                <div class={style.mid_intro}>中间文案或者图片</div>
                <Roll />
            </div>
        </div>
}
 
export default Index;

Explanation of the above code:

        Pay attention to the position attribute setting of the main.roll class, which is usually relative, so that the Snake component can be surrounded by mid_intro.

 Components:

import style from "./style.less";
import React, { useEffect, useRef, useState } from "react";

 
const Roll = () => {
  //计数:一般是图片总数
  const [count, setCount] = useState(0);
  
  const timer = useRef(null);
  useEffect(() => {
    if (timer.current != null) {
      clearTimeout(timer.current);
      timer.current = null;
    }
    timer.current = setTimeout(() => {
      if (count == 20) {  //当计数等于最高图片时,从0图片开始
        setCount(0);
        return;
      }
      setCount(() => count + 1);
    }, 60);//每隔60毫秒执行一次
    return () => {
      clearTimeout(timer.current);
    };
  }, [count]);
  return React.useMemo(
    () => (
      <div>
        //有多少张图片循环切换
        {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].map((index) => {
          return (
            <img
              key={index}
              src={`../images/t${index}.png`}
              alt=""
              className={style.img_roll}
              style={
   
   { display: index === count ? "inherit" : "none" }}
            />
          );
        })}
      </div>
    ),
    [count]
  );
};
 
export default Roll;

The effect of the above code is actually to switch between multiple pictures to achieve the desired effect. 

 css:

#根据自己需求调整属性
.img_roll {
  position: absolute;
  top: -2rem;
  left: -2.2022rem;
  width: 12.40667rem;
}

 

Guess you like

Origin blog.csdn.net/zhoupenghui168/article/details/133161167