簡體   English   中英

在 React 中,如何使用 Ref 獲取 Element 屬性的值?

[英]In React, how can I get the value of Element's attribute using Ref?

我想要做

function MyComponent () {

    const myRef = useRef(null)

    const myValue = useMemo(() => (myRef.current.someKey), [])

    return <div ref={myRef} />
}

但它不起作用,因為有時在設置 myValue 時 myRef 尚未加載(因此 myRef.current 為空),並且我不知道在加載完成后我應該如何重置 myValue。

function MyComponent() {
  const [myValue, setMyValue] = useState("Loading...");
  const myRef = useRef(null);

  useEffect(() => {
    setMyValue(myRef?.current.dataset.value);
  }, [myRef]);

  return (
    <div ref={myRef} data-value="foo">
      {myValue}
    </div>
  );
}

暫無
暫無

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

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