簡體   English   中英

React 導入的組件沒有完全工作

[英]React imported component is not working completely

我真的是 React 的新手,我已經嘗試了一段時間來滾動到頂部 function。 使用現有的教程和谷歌上的所有內容,我制作了這個組件:

Import React, { useState, useEffect } from "react";


export default function ScrollToTop() {
const [isVisible, setIsVisible] = useState(false)

const toggleVisibility = () => {
    if(window.pageYOffset > 300) {
        setIsVisible(true);
    } else {
        setIsVisible(false);
    }
};

const ScrollToTop = () => {
    window.scrollTo({
        top: 0,
        behavior: "smooth",
    });
};

useEffect(() => {
    window.addEventListener('scroll', toggleVisibility);

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

if (!isVisible) {
    return false
}

return (
<button className="button" onClick={ScrollToTop}>
    <div className="button__arrow button__arrow--up"></div>
</button>
)
};

問題是當我在 App.js 中導入它時它不能正常工作,滾動部分工作得很好,但它只是停留在頁面底部而不是在一定量的滾動后出現。 這是 App.js:

return (
<div>
  {loading ? (
    <h1>Loading...</h1>
  ) : (
    <>
    <Navbar />
      <div className="Grid-container">
        {pokemonData.map((pokemon, i) => {
          return <Card key={i} pokemon={pokemon} />;
        })}
      </div>
    <ScrollToTop/>
    </>
  )}
</div>
);
}

我在您的ScrollTop實現中沒有看到任何明顯的問題,即使在滾動回頂部后,滾動到頂部按鈕也會保留在頁面上,但我確實看到了優化的空間。

  1. 對於onScroll事件,最好使用被動偵聽器。
  2. 在安裝useEffect時立即調用toggleVisibility以確保正確的初始 state。
  3. 將 Boolean Zen 應用於可見性切換器; 使用 boolean 比較的結果更新isVisible state。
  4. 只需有條件地在一次返回中呈現按鈕。

代碼:

function ScrollToTop() {
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = () => {
    setIsVisible(window.pageYOffset > 300);
  };

  const ScrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth"
    });
  };

  useEffect(() => {
    toggleVisibility();

    window.addEventListener("scroll", toggleVisibility, { passive: true });

    return () => {
      window.removeEventListener("scroll", toggleVisibility, { passive: true });
    };
  }, []);

  return isVisible ? (
    <button className="button" onClick={ScrollToTop}>
      <div className="button__arrow button__arrow--up">TOP</div>
    </button>
  ) : null;
}

編輯 react-imported-component-is-not-working-completely

如果您的實施和使用仍然存在問題,請嘗試創建一個代碼框來重現我們可以實時檢查和調試的問題。

暫無
暫無

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

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