"> 无法访问反应中的元素引用-PHP中文网问答
无法访问反应中的元素引用
P粉136356287
P粉136356287 2023-09-08 09:51:59
0
1
444

我正在尝试使用 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 = ( 
{props.children}
); 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 ( ); }); 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]);
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责声明 Sitemap
    PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!