簡體   English   中英

如何通過 useRef 鈎子使用樣式?

[英]How to use styling with useRef hook?

我正在嘗試使用 useRef 通過單擊按鈕來移動組件的項目。 我嘗試了以下代碼:

export const List: React.FC = () => {
  const listRef: any = useRef(null);
  const handleSliderClick = (direction: string) => {
    if (direction === "left") {
      console.log(listRef.current, "refff");
      listRef.current.style.transform = `translateX(230px)`;
    }
  };
  return (
    <div className="movie-list">
      <span className="list-title">Continue to watch</span>
      <div className="wrapper">
        <ArrowBackIosOutlined
          className="slider-arrow left"
          onClick={() => handleSliderClick("left")}
        />
      </div>
    </div>
  );
};

我收到錯誤消息“類型錯誤:無法讀取 null 的屬性(讀取‘樣式’)”。 useRef 的正確使用方法是什么?

需要將 ref 分配給要操作的元素。 例如

  <div className="wrapper" ref={listRef}>

您需要將 ref 分配給元素,然后它才會起作用。

    <div className="wrapper" ref={listRef}>

暫無
暫無

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

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