【发布时间】:2021-09-18 11:29:15
【问题描述】:
我正在为我的 div 添加一个高度,如下所示:
const parentRef = useRef();
useEffect(() => {
let collapseHeight = parentRef.current.scrollHeight
const collapse = document.querySelector('.collapse-content-parent')
collapse.style.height = collapseHeight + "px"
}, []);
当同一个组件有多个实例时,这只是选择页面上的第一个 div。
我想做一些事情,比如将 querySelector 换成我的 ref,所以它对组件是特定的:
const parentRef = useRef();
useEffect(() => {
let collapseHeight = parentRef.current.scrollHeight
parentRef.style.height = collapseHeight + "px"
}, []);
但上面的结果是:
TypeError: Cannot set properties of undefined (setting 'height')
【问题讨论】: