我正在嘗試使用 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;
您收到錯誤是因為第一次執行 useEffect 時
modalRef.current
為undefined
。只需新增 null 檢查或if(modalRef.current)
條件即可避免此錯誤。如果 useEffect 未執行,您可能還需要更新依賴項。