首页 > 解决方案 > 安装后 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,我也不确定我能否获得正确的高度。任何想法 ?谢谢

标签: reactjsreact-hooksuse-effectuse-ref

解决方案


将您的状态elementHeight置于useEffect依赖状态。当状态改变时useRef得到更新的值。

useEffect(()=>{
  if(portalRef.current){
    const portalDimensions = portalRef.current.getBoundingClientRect();
    setElementHeight(portalDimensions.height);
     }
 }, [elementHeight]);

推荐阅读