首页 > 解决方案 > 如何存储到数组

问题描述

我正在使用 React Hooks 和 jQuery 制作一个方法,其工作原理如下:

按下该ctrl键时,可以从表中选择多行。我只想在单击 ctrl 时将此行的 id 存储在数组中,但是每次单击一行时,数组似乎都会重新启动,而不是存储单击行的所有 id。

此外,由于此 jquery 代码中不存在数组,因此我使用了一个钩子。请问有人可以帮我吗?这是我的代码,在此先感谢。

 const Mapa = (props) => {
  const [groupOfIntersections, setGroupOfIntersections] = useState('');
  const arrayOfInt = [];

  $('.ui.small.celled.table tbody tr').on('click', (e) => {
    if (e.ctrlKey) {
      if($(e.target.parentNode).hasClass("active")) {
        $(e.target.parentNode).removeClass("active");
      } else {
        arrayOfInt.push($(e.target.parentNode).attr('class'));
        console.log('arrayOfInt', arrayOfInt);
        setGroupOfIntersections(arrayOfInt);
        $(e.target.parentNode).addClass("active");
      }
    } else if (!e.ctrlKey){
      $('.ui.small.celled.table tbody tr').removeClass("active");
      $(e.target.parentNode).addClass("active");
    }
  });
  
  console.log('groupOfIntersections', groupOfIntersections);
  console.log('arrayOfInt', arrayOfInt);

      .
      .
      .
};

标签: javascriptjqueryreactjsmeteorreact-hooks

解决方案


这个arrayOfInt常量有问题,实际上你不需要额外的对象,因为你可以使用现有的groupOfIntersections对象来执行所有的操作。

 const Mapa = (props) => {
   const [groupOfIntersections, setGroupOfIntersections] = useState('');       

$('.ui.small.celled.table tbody tr').on('click', (e) => {
    if (e.ctrlKey) {
      if($(e.target.parentNode).hasClass("active")) {
        $(e.target.parentNode).removeClass("active");
      } else {
        let tempGroup = [...groupOfIntersections]
        tempGroup.push($(e.target.parentNode).attr('class'));
        console.log('tempGroup', tempGroup);
        setGroupOfIntersections(tempGroup);
        $(e.target.parentNode).addClass("active");
      }
    } else if (!e.ctrlKey){
      $('.ui.small.celled.table tbody tr').removeClass("active");
      $(e.target.parentNode).addClass("active");
    }
  });     
  console.log('groupOfIntersections', groupOfIntersections);
  console.log('arrayOfInt', tempGroup);

      .
      .
      .
};

推荐阅读