Resize事件后,来自Ref属性的对象值返回为null

时间:2019-03-12 14:09:19

标签: javascript reactjs

我是React的新手,所以我可能只是走错了路。

我在YouTube上关注了本教程,并试图在功能组件Tutorial Here中复制它

下面是我的组件

import React, { useState, useRef, useEffect } from 'react';
import _ from "lodash";

const Tabs = (props) => {
   const [sizes, updateSizes] = useState({});

   useEffect(() => {
      getSizes();
      window.addEventListener("resize", _.debounce(() => getSizes() ));
   },[props]);

   let els = {};

   const tabsRef = useRef(null);

   const getSizes = () => {
      const rootBounds = tabsRef.current.getBoundingClientRect();

      const size = {};

      /* when this function gets called with the resize event els is returned as
      {loginTab: null, signupTab: null}
      when on initial load it is
      {loginTab: div.Tab.Tab--active, signupTab: div.Tab}*/
      Object.keys(els).forEach((key) => {
         const el = els[key];
         const bounds = el.getBoundingClientRect();
         const left = bounds.left - rootBounds.left;
         const right = rootBounds.right - bounds.right;

         size[key] = { left, right };
      });

      updateSizes(size);

      return size;

   }

   return (
      <div className="Tabs" ref={tabsRef}>
         {React.Children.map(props.children, (child, i) => {
            return (
               <div
                  className={child.key === props.active ? 'Tab Tab--active' : 'Tab'}
                  onClick={() => {
                     props.onChange(child.key);
                  }}
                  ref={el => els[child.key] = el}
               >
                  {child}
               </div>
            )
         })}
         <div className="Tabs-underline"></div>
      </div>
   );
};

export default Tabs;

这在组件的初始加载上按预期工作,当我调度调整大小事件时,els返回

{
    loginTab: null, 
    signupTab: null
}

在初始加载时返回

{
    loginTab: div.Tab.Tab--active, 
    signupTab: div.Tab
}

在这种情况下,有没有更好的方法使用ref属性来返回所有正确的元素,因此它们不会返回为null?

0 个答案:

没有答案