無法存取反應中的元素引用
P粉136356287
P粉136356287 2023-09-08 09:51:59
0
1
515

我正在嘗試使用 React 實作一個模態,在這個模態中我想相對於觸發它的元素(不是父元素)定位模態。 在此設定中,我可以訪問觸發元素的引用,就像您在此處看到的那樣

console.log(
          "console button triggering modal offset" + event.target.offsetTop
        );

但我無法存取對模式的引用,此程式碼會產生錯誤

useEffect(() => {
    console.log("loggin ref width   " + modalRef.current.offsetWidth);
  }, [modalRef]);

我收到此錯誤訊息

Uncaught TypeError: Cannot read properties of undefined (reading 'offsetWidth')
    at UserParamModal2.js:44:1
    at commitHookEffectListMount (react-dom.development.js:23150:1)
    at commitPassiveMountOnFiber (react-dom.development.js:24926:1)
    at commitPassiveMountEffects_complete (react-dom.development.js:24891:1)
    at commitPassiveMountEffects_begin (react-dom.development.js:24878:1)
    at commitPassiveMountEffects (react-dom.development.js:24866:1)
    at flushPassiveEffectsImpl (react-dom.development.js:27039:1)
    at flushPassiveEffects (react-dom.development.js:26984:1)

當我刪除 CSSTransition 元件時,一切都很好, 這是完整的程式碼。 我將不勝感激任何幫助。

import {
  React,
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import ReactDOM from "react-dom";

import "./UserParamModal2.css";
import { CSSTransition } from "react-transition-group";

const UserParamModalOverlay = forwardRef((props, ref) => {
  const content = (
    <div className={`userparammodal ${props.className}`} ref={ref}>
      {props.children}
    </div>
  );
  return ReactDOM.createPortal(
    content,
    document.getElementById("modal-user-param")
  );
});

const UserParamModal2 = forwardRef((props, ref) => {
  const [visible, setVisible] = useState(false);
  const modalRef = useRef();

  useImperativeHandle(ref, () => {
    return {
      toggle(event) {
        console.log(
          "console button triggering modal offset" + event.target.offsetTop
        );
        setVisible((prev) => {
          return !prev;
        });
      },
    };
  });

  useEffect(() => {
    console.log("loggin ref width   " + modalRef.current.offsetWidth);
  }, [modalRef]);

  return (
    <CSSTransition
      in={visible}
      mountOnEnter
      unmountOnExit
      timeout={200}
      classNames="userparammodal"
    >
      <UserParamModalOverlay {...props} ref={modalRef}></UserParamModalOverlay>
    </CSSTransition>
  );
});

export default UserParamModal2;

P粉136356287
P粉136356287

全部回覆(1)
P粉546138344

您收到錯誤是因為第一次執行 useEffect 時 modalRef.currentundefined。只需新增 null 檢查或 if(modalRef.current) 條件即可避免此錯誤。

如果 useEffect 未執行,您可能還需要更新依賴項。

useEffect(() => {
    console.log("loggin ref width   " + modalRef.current?.offsetWidth);
  }, [modalRef.current]);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板