reactjs - 安装后 React Ref 获取属性
问题描述
我试图在安装后获取元素高度。它们的高度可以根据子元素改变,这就是为什么我不能给出静态高度。
const PositionedComponent = styled.div`
position: fixed;
z-index: 999999999;
max-height: 300px;
overflow:unset;
${props =>
!props.hasOverflow && `
overflow: hidden;
overflow-y: auto;
`}
`;
....
const [elementHeight,setElementHeight] = useState(0);
const portalRef = useRef(null);
const childrenContainerRef = useRef(null);
useEffect(()=>{
if(portalRef.current){
const portalDimensions = portalRef.current.getBoundingClientRect();
setElementHeight(portalDimensions.height);
}
}, [portalRef]);
....
return (
isVisible && (
<Root>
{ReactDOM.createPortal(
<PositionedComponent
ref={portalRef}
style={combinedStyles}
hasOverflow={hasOverflow}
id='positioned-component'
>
<ChildrenContainer ref={childrenContainerRef}>
{children}
</ChildrenContainer>
</PositionedComponent>,
document.getElementById(portalContainerName)
)}
</Root>
)
);
它不会再次进入 useEffect 。即使它再次进入 useEffect,我也不确定我能否获得正确的高度。任何想法 ?谢谢
解决方案
将您的状态elementHeight
置于useEffect
依赖状态。当状态改变时useRef
得到更新的值。
useEffect(()=>{
if(portalRef.current){
const portalDimensions = portalRef.current.getBoundingClientRect();
setElementHeight(portalDimensions.height);
}
}, [elementHeight]);
推荐阅读
- html - 如何将 html 对话框与 Firefox 左对齐或右对齐?
- javascript - 打字稿中具有通用键的对象
- c++ - UE4 C++ 无法识别的类型“FMasterItem” - 类型必须是 UCLASS、USTRUCT 或 UENUM
- c# - uGUI 文本字段,如何删除“替换字符”(uFFFD aka �)?
- google-bigquery - 在 BiqQuery extract_table 中强制覆盖
- null - 参数名称、姓氏、出生日期、出生地、ID
- sql - 对于这个 SQL Zoo 问题,哪个查询更快
- postgresql - Debezium CDC 连接器的 Postgres 11 设置
- spring-boot - Spring Boot 测试 @After 在下一次测试之前不删除行
- java - 如何在 Android 中向包含外键的表中插入数据