Как я могу сохранить свои изменения после того, как они не пересекаются с моим элементом?

Я использую реакцию, и я хочу сделать некоторую анимацию, когда окно просмотра находится на моем нужном элементе, но я хочу запустить его только один раз, поэтому, когда значение наблюдателя равно false, мой стиль элемента не меняется снова на начало.

Я использую styled-components для стилизации

HomeSection.Projects = function HomeSectionProjects({ children, ...rest }) {
  const ref = useRef(null);
  const [isVisible, setVisible] = useState(false);

  const callbackFn = (entries) => {
    const [entry] = entries;
    setVisible(entry.isIntersecting);
  };

  useEffect(() => {
    const options = {
      root: null,
      rootMargin: "0px",
      threshold: 1,
    };

    const observer = new IntersectionObserver(callbackFn, options);
    if (ref.current) observer.observe(ref.current);
  }, [ref]);

  return <Projects ref={ref}>{children}</Projects>;
};

Итак, вот мой стилизованный комп

export const Projects = styled.div`
  width: 70%;
  height: 70vh;
  display: flex;
  opacity: 1;
  margin-bottom: 30vh;
  justify-content: flex-start;
  align-items: center;
  position: relative;
  transition: opacity 1.5s ease-out;

  @media screen and (max-width: 763px) {
    margin-bottom: 20%;
    height: 50vh;
    align-items: center;
    flex-direction: column;
    padding-top: 10%;
    width: 100%;
  }

  &:hover ${ImageDiv} {
    transform: scale(0.9);
  }

  &:hover ${Title} {
    /* transform: scale(1.4); */
    font-size: 8rem;

    @media screen and (max-width: 763px) {
      font-size: 3.2rem;
    }
  }

  &:hover ${TitleInfo} {
    font-size: 2rem;
    bottom: -5%;

    @media screen and (max-width: 763px) {
      font-size: 1.5rem;
    }
  }

  &:hover ${Info} {
    left: -8%;

    @media screen and (max-width: 763px) {
    }
  }
`;

Как я могу достичь своей цели здесь?


person Angga Ardinata    schedule 03.03.2021    source источник


Ответы (1)


Вы можете перестать наблюдать за элементом, как только он станет видимым. Также ваш callbackFn не обязательно должен быть снаружи в теле функции.

useEffect(() => {
    const options = {
      root: null,
      rootMargin: "0px",
      threshold: 1,
    };

   const callbackFn = (entries) => {
    const [entry] = entries;
    if(entry.isIntersecting)
    {
    setVisible(true);
    observer.unobserve(entry.target);
    }
  };

    const observer = new IntersectionObserver(callbackFn, options);
    if (ref.current) observer.observe(ref.current);

  }, [ref]);
person Lakshya Thakur    schedule 03.03.2021