简体   繁体   English

无法读取 null 的属性“offsetWidth”?

[英]Cannot read property 'offsetWidth' of null?

i am trying to covert a small jquery component to react .but i am getting this issue Cannot read property 'offsetWidth' of null我试图隐藏一个小的 jquery 组件来做出反应。但是我遇到了这个问题Cannot read property 'offsetWidth' of null

here is jquery simple component http://jsfiddle.net/abhitalks/860LzgLL/这是 jquery 简单组件http://jsfiddle.net/abhitalks/860LzgLL/

what component does it show "menu or tab list" .If window screen is decrease it hide menu and move to dropdown like this什么组件显示“菜单或标签列表”。如果窗口屏幕缩小,它会隐藏菜单并移动到下拉菜单在此处输入图片说明

I tried to implement is react .我试图实现的是 react 。

My approach is我的方法是

  1. First i am calculate the width of li 's or sum of all width of li.首先,我计算li的宽度或li的所有宽度的总和。
  2. Also get the width of container.同时获取容器的宽度。
  3. if sum of li width is greater I set the threshold .如果 li 宽度的总和更大,我set the threshold render using threshold value使用阈值渲染

but when I am resize my component I am getting below error但是当我调整我的组件大小时,我遇到了错误

**Cannot read property 'offsetWidth' of null ** **无法读取 null 的属性“offsetWidth”**

here is my code https://stackblitz.com/edit/react-wmtunp?file=src%2FApp.js这是我的代码https://stackblitz.com/edit/react-wmtunp?file=src%2FApp.js

import React, { useState, useRef, createRef, useEffect } from 'react';
import './style.css';

const data = [
  'Option One',
  'Option_hellodummyhhhsdshshshd',
  'Option Three',
  'Option Four',
  'Option Five'
];

export default function App() {
  const [state, setState] = useState(data);
  const [threshold, setThreshold] = useState(-1);

  const liRefs = useRef([]);
  const ulRef = useRef(null);

  liRefs.current = state.map((_, i) => liRefs.current[i] ?? createRef());

  const adjustItems = function() {
    var skipLoop = false,
      w2W = ulRef.current.offsetWidth,
      index = -1,
      totalW = 0;
    liRefs.current.map(function(li, key) {
      if (skipLoop) {
        return;
      }
      totalW += li.current.offsetWidth;
      if (totalW > w2W) {
        skipLoop = true;
        index = key;
      }
      setThreshold(index);
    });
  };
  useEffect(() => {
    adjustItems();
    window.addEventListener('resize', adjustItems);
    return () => window.removeEventListener('resize', adjustItems);
  }, []);
  return (
    <div>
      <ul id="menu" ref={ulRef}>
        {state.map((i, index) =>
          threshold == -1 ? (
            <li ref={liRefs.current[index]} key={index}>
              {i}
            </li>
          ) : threshold !== -1 && threshold >= index ? (
            <li ref={liRefs.current[index]} key={index}>
              {i}
            </li>
          ) : (
            <></>
          )
        )}
      </ul>
      <ol>
        <li>
          Collected
          <ul id="submenu">
            {state.map((i, index) =>
              threshold !== -1 && threshold <= index ? (
                <li ref={liRefs.current[index]} key={index}>
                  {i}
                </li>
              ) : (
                <></>
              )
            )}
          </ul>
        </li>
      </ol>
    </div>
  );
}

My functionality break when I am resizing the window.当我调整窗口大小时,我的功能会中断。 I am new in react js .Is there problem in my approach ?我是 react js 的新手。我的方法有问题吗? any suggestion ?有什么建议吗?

Just try using ?尝试使用 ? this operator, since when you are resizing it might get null or undefined based on condition but by putting this condition it will help you put an "and" check if property value exists or not.这个运算符,因为当你调整它的大小时,它可能会根据条件得到 null 或 undefined 但通过放置这个条件,它将帮助你放置一个“和”检查属性值是否存在。

 import React, { useState, useRef, createRef, useEffect } from 'react'; import './style.css'; const data = [ 'Option One', 'Option_hellodummyhhhsdshshshd', 'Option Three', 'Option Four', 'Option Five' ]; export default function App() { const [state, setState] = useState(data); const [threshold, setThreshold] = useState(-1); const liRefs = useRef([]); const ulRef = useRef(null); liRefs.current = state.map((_, i) => liRefs.current[i] ?? createRef()); const adjustItems = function() { let skipLoop = false, w2W = ulRef.current.offsetWidth, totalW = 0; liRefs.current.map((li, key) => { if (skipLoop) { return; } totalW += li?.current?.offsetWidth; if (totalW > w2W) { skipLoop = true; setThreshold(key); } else { setThreshold(liRefs.current.length); } }); }; useEffect(() => { adjustItems(); window.addEventListener('resize', adjustItems); return () => window.removeEventListener('resize', adjustItems); }, []); return ( <div> <ul id="menu" ref={ulRef}> {state.map((i, index) => threshold == -1 ? ( <li ref={liRefs.current[index]} key={index}> {i} </li> ) : threshold !== -1 && threshold > index ? ( <li ref={liRefs.current[index]} key={index}> {i} </li> ) : ( <></> ) )} </ul> <ol> <li> Collected <ul id="submenu"> {state.map((i, index) => threshold !== -1 && threshold <= index ? ( <li ref={liRefs.current[index]} key={index}> {i} </li> ) : ( <></> ) )} </ul> </li> </ol> </div> ); }

You can reference it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining您可以参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

暂无
暂无

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

相关问题 Google MAP API未捕获TypeError:无法读取null的属性'offsetWidth' - Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null Google Map API BackBoneJS无法读取null的属性&#39;offsetWidth&#39; - Google Map API BackBoneJS Cannot read property 'offsetWidth' of null Google Map API,未捕获的TypeError:无法读取null的属性“ offsetWidth” - Google map API, Uncaught TypeError: Cannot read property 'offsetWidth' of null Enyo JS Uncaught TypeError:无法读取null的属性&#39;offsetWidth&#39; - Enyo JS Uncaught TypeError: Cannot read property 'offsetWidth' of null 流星模板异步呈现-无法读取null的属性“ offsetWidth” - Meteor template rendered asynchronously - Cannot read property 'offsetWidth' of null 无法使用Bootstrap Carousel读取未定义的属性&#39;offsetWidth&#39; - Cannot read property 'offsetWidth' of undefined with Bootstrap Carousel Bootstrap Carousel:无法读取未定义的属性&#39;offsetWidth&#39; - Bootstrap Carousel: Cannot read property 'offsetWidth' of undefined 轮播无法正常工作,无法读取未定义的属性“ offsetWidth” - Carousel not working, Cannot read property 'offsetWidth' of undefined 错误:未被捕获的TypeError:无法在angularjs中读取Google地图的null属性&#39;offsetWidth&#39; - Error: Uncaught TypeError: Cannot read property 'offsetWidth' of null in angularjs for google maps google maps api v3未捕获typeError:无法读取null的属性“ offsetWidth” - google maps api v3 uncaught typeError: Cannot read property 'offsetWidth' of null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM