Javascript 在React中,如何获取元素';s属性使用Ref?

Javascript 在React中,如何获取元素';s属性使用Ref?,javascript,reactjs,Javascript,Reactjs,我想做什么 function MyComponent () { const myRef = useRef(null) const myValue = useMemo(() => (myRef.current.someKey), []) return <div ref={myRef} /> } 函数MyComponent(){ 常量myRef=useRef(空) const myValue=useMoom(()=>(myRef.current.so

我想做什么

function MyComponent () {

    const myRef = useRef(null)

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

    return <div ref={myRef} />
}
函数MyComponent(){
常量myRef=useRef(空)
const myValue=useMoom(()=>(myRef.current.someKey),[])
返回
}
但它不起作用,因为有时在设置myValue时myRef尚未加载(因此myRef.current为null),我不知道加载完成后应该如何重置myValue。

函数MyComponent(){
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>
  );
}
const[myValue,setMyValue]=useState(“加载…”); const myRef=useRef(null); useffect(()=>{ setMyValue(myRef?.current.dataset.value); },[myRef]); 返回( {myValue} ); }
尝试使用useffectfirst检查myRef.current值将
myRef.current
添加到
usemo
依赖项数组中。当前,对于空数组
useMoom
值将仅在第一次渲染时计算。