我正在尝试使用 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 未运行,您可能还需要更新依赖项。