javascript 如何访问数据集的属性?

2vuwiymt  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(113)

我从code pen复制了一些普通的HTML、CSS和JavaScript代码,但是当我试图转换成React时,它说它不能读取null reading(数据集)的属性
JS代码:

const wrapper = document.getElementById("wrapper");

const rand = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const uniqueRand = (min, max, prev) => {
  let next = prev;
  
  while(prev === next) next = rand(min, max);
  
  return next;
}

const combinations = [
  { configuration: 1, roundness: 1 },
  { configuration: 1, roundness: 2 },
  { configuration: 1, roundness: 4 },
  { configuration: 2, roundness: 2 },
  { configuration: 2, roundness: 3 },
  { configuration: 3, roundness: 3 }
];`your text`

let prev = 0;

setInterval(() => {
  const index = uniqueRand(0, combinations.length - 1, prev),
        combination = combinations[index];
  

  wrapper.dataset.configuration = combination.configuration;
  wrapper.dataset.roundness = combination.roundness;
  
  prev = index;
}, 1000);

用于此的HTML代码:

<div id="wrapper"ref={myContainer} data-configuration="1" data-roundness="1">
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
        <div className="shape"></div>
</div>

我会附加的CSS,但这是太长的方式附加...
我试过使用useRef,但是不起作用。我必须找到一些方法来解决这个问题。
未捕获的类型错误:无法读取null的属性(正在读取"dataset")

dgiusagp

dgiusagp1#

很可能发生的情况是,在将 Package 器<div>装入DOM之前查询它,因此wrapper变量为null,因此出现错误消息。
一个非常简单的解决方法是在需要之前在setInterval中查询Element:

setInterval(() => {
  const index = uniqueRand(0, combinations.length - 1, prev),
    combination = combinations[index];

  const wrapper = document.getElementById("wrapper");
  if (wrapper) {
    wrapper.dataset.configuration = combination.configuration;
    wrapper.dataset.roundness = combination.roundness;
  }

  prev = index;
}, 1000);

演示:https://codepen.io/ghybs/pen/dyjKQGg

相关问题