繁体   English   中英

如何修复无法读取 null 的属性“clientWidth”?

[英]How to fix Cannot read property 'clientWidth' of null?

调整窗口大小时出现错误“无法读取 null 的属性‘clientWidth’”。 我想,这是因为,我得到 ref null。 知道我该如何解决吗?

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

const data = [
  "Some short text",
  "Some text that is a little bit longer",
  "Some text that will need to wrap but still fits on two lines",
  "A massive range of hammer drill machines and rotary hammers for SDS-plus accessory tools."
];
const TooltipDiv = props => {
  const divRef = useRef(null);
  const [allowTooltip, setAllowTooltip] = useState(false);
  useEffect(() => {
    if (!tooltip && divRef.current.scrollWidth > divRef.current.clientWidth) {
      setTooltip(true);
    } else if (window.addEventListener) {
      window.addEventListener('resize', () => {
        if (!tooltip && divRef.current.scrollWidth > divRef.current.clientWidth) {
            setTooltip(true);
        }
      })
    }
  }, [tooltip, divRef]);
  if (allowTooltip) {
    return (
      <Tooltip title={props.text}>
        <div ref={divRef} className={props.className}>
          {props.text}
        </div>
      </Tooltip>
    );
  }
  return (
    <div ref={divRef} className={props.className}>
      {props.text}
    </div>
  );
};
function App(props) {
  return (
    <>
      {data.map(text => {
        return (
          <>
            <TooltipDiv text={text} className={props.classes.listItem} />
          </>
        );
      })}
    </>
  );
}

调整窗口大小时出现错误“无法读取 null 的属性‘clientWidth’”。 我想,这是因为,我得到 ref null。 知道我该如何解决吗?

window.addEventListener正在尝试读取尚不存在的值。 此时 divRef 为空。

我认为您应该尝试测试 div.current 的存在,然后执行您的if语句:

if(tooltip && divRef.current && divRef.current.scrollWidth && divRef.current.clientWidth){
  //your statement
}

另外,尝试在没有[divRef, tooltip]情况下执行操作[divRef, tooltip]因为您希望它只执行一次 ( [] ),我想

暂无
暂无

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

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