簡體   English   中英

觸發 useState

[英]Triggering useState

我有一個組件並使用不同的道具有條件地渲染它。

      {activeNavItem === 'Concept Art' ? (
        <Gallary
          images={conceptArtImages}
          sectionRef={sectionRef}
        />
      ) : (
        <Gallary
          images={mattePaintingImages}
          sectionRef={sectionRef}
        />
      )}

這個組件有useState(false)useEffect鈎子。 useEffect確定屏幕位置何時到達 dom 元素並觸發useStatetrueelementPosition < screenPosition 然后我的state在 dom 元素上觸發類: state ? 'animationClass' : '' state ? 'animationClass' : ''

const Gallary = ({ images, sectionRef }) => {
  const [isViewed, setIsViewed] = useState(false);

  useEffect(() => {
    const section = sectionRef.current;

    const onScroll = () => {
      const screenPosition = window.innerHeight / 2;
      const sectionPosition = section.getBoundingClientRect().top;
      console.log(screenPosition);

      if (sectionPosition < screenPosition) setIsViewed(true);
    };

    onScroll();
    window.addEventListener('scroll', onScroll);

    return () => {
      window.removeEventListener('scroll', onScroll);
    };
  }, [sectionRef]);

  return (
    <ul className="section-gallary__list">
      {images.map((art, index) => (
        <li
          key={index}
          className={`section-gallary__item ${isViewed ? 'animation--view' : ''}`}>
          <img className="section-gallary__img" src={art} alt="concept art" />
        </li>
      ))}
    </ul>
  );
};

問題:它適用於我的第一次渲染。 但是當我用不同的道具切換組件時,我的state最初是true ,我沒有動畫。

我注意到如果我有兩個組件( ComponentA, ComponentB )而不是一個( ComponentA )它工作正常。

當您的組件不在視圖中時,請嘗試將isViewed設置為 false:

if (sectionPosition < screenPosition && !isViewed){
setIsViewed(true);
}
else{
if(isViewed) 
   setIsViewed(false);
}

你可以這樣做:

if (sectionPosition < screenPosition && !isViewed){
setIsViewed(state=>!state);
}
else{
if(isViewed) 
   setIsViewed(state=>!state);
}

加上不需要多次渲染同一個組件,你只能改變道具:

  <Gallary
      images={activeNavItem === 'ConceptArt'?conceptArtImages:mattePaintingImages}
      sectionRef={sectionRef}
    />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM