【问题标题】:React Ref get properties after mount安装后 React Ref 获取属性
【发布时间】:2021-10-03 03:31:02
【问题描述】:

我试图在安装后获取元素高度。 它们的高度可以根据子元素改变,这就是为什么我不能给出静态高度。

 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,我也不确定我能否获得正确的高度。 任何想法 ? 谢谢

【问题讨论】:

  • 如果我是对的,你想在安装元素时获取高度,然后更新是否会改变高度?
  • @ЖнецЪ 是的,没错

标签: reactjs react-hooks use-effect use-ref


【解决方案1】:

把你的状态 elementHeight 放到 useEffect 依赖。当状态改变时useRef 获取更新值。

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

【讨论】:

  • 我只是在 useEffect 中设置 elementHeight 为什么将 elementHeight 添加到依赖项中会有所不同?
  • UseRef 不调用重新渲染,因为它用于静态值。当你把 use 放在 useEffect 依赖中时,什么也没发生。为此使用 useState 依赖项。当与setElementHeight 调用时,您会更改状态,useEffect 更新组件,UseRef 获取新值。
  • That working example 如果你尝试改变文字,宽度也会改变。
  • 您使用了ReactDOM.createPortal 是模态还是弹出窗口?如果是这样,请将isVisible 依赖项放入useEffect。即更新组件的触发器。
  • 您的示例 scnerio 与我的不同,顺便说一句,是的,它的某种模态子值带有承诺,也许这就是您的示例有效而不是我的原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2021-12-31
  • 2022-09-24
  • 2019-05-12
  • 2022-01-07
  • 1970-01-01
相关资源
最近更新 更多