繁体   English   中英

无法获取ref.current.offsetWidth

[英]Can't get ref.current.offsetWidth

我试图做contextMenu。

我想从ref.current获取offsetWidth和offsetHeight,但console.log打印未定义。

const ContextMenu: React.FC<ContextMenuProps> = props => {
  const thisComponent = useRef(null);
  const [isVisible, setIsVisible] = useState<boolean>(false);
  let thisComponentHeight = null;
  let thisComponentWidth = null;

  useEffect(() => {
    document.addEventListener("contextmenu", contextMenuHandler);
    if (thisComponent && thisComponent.current) {
      thisComponentWidth = thisComponent.current;
      thisComponentHeight = thisComponent.current;
      console.log(thisComponent.current)
    }
  }, []);

  return (
    <Column ref={thisComponent}>
      <div>test</div>
      <div>test2</div>
    </Column>
  );
};

export default ContextMenu;

这是console.log(thisComponent.current);的图片console.log(thisComponent.current);

在此处输入图片说明

那个Column组件看起来像是属于另一个库,而不是React的本机库,因此它们可能在current对象中定义了自己的属性集。 只需将Column包装在divspan ,然后将该标记提供给ref 您将能够获取offsetWidth以及本机DOM属性。

  return (
    <div ref={thisComponent}>
      <Column>
        <div>test</div>
        <div>test2</div>
      </Column>
    </div>
  );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM