我有一个纯粹用功能组件构建的反应应用程序。我想在屏幕上呈现元素后获取元素的高度,以相应地更改其父级的大小。
有基于类的应用程序的解决方案,但我找不到任何功能组件。
我从答案中尝试了这个解决方案,但它没有运行 useEffect 钩子
这是从我的组件中提取的代码
import React, {useRef, useEffect} from 'react';
import {
MenuContainer,
GrayBox,
Wrapper
} from '../LayersMenu/LayerMenu.styles';
export const Component = ({ category, showStatistics }) => {
const grayBoxRef= useRef(null);
const wrapperRef= useRef(null);
const testRef= useRef(null);
useEffect(()=>{
const height = wrapperRef.current.offsetHeight;
console.log(height,'check');
}, [wrapperRef])
useEffect(()=>{
const height = testRef.current.offsetHeight;
console.log(height,'check2');
},[testRef]);
return (
<MenuContainer ref={testRef}>
<GrayBox ref={grayBoxRef}>
<Wrapper ref={wrapperRef} hasAnyAllowedStats={showStatistics}>
</Wrapper>
</GrayBox>
</MenuContainer>
);
};
PS:接受的答案不适用于我的答案,但它适用于他在答案中添加的项目,所以我猜我的项目结构有问题或不完全确定。
非常感谢您的回答