我遇到以下情况,我想知道indexOf值以便以后在代码中使用该知识。但是,我尝试了多种不同的方法来获得价值,但我似乎并没有正确地做到这一点。在下面的代码中,我尝试了几种搜索Stackoverflow时发现的不同方法。到目前为止,它们都返回-1,这意味着我的代码有问题或目前无法找到其他问题。

仅供参考,selectedGroup是一个内部包含对象的数组,如下所示:
[{label: "somelabel", value: 100}]
取决于用户,可以有很多。

码:

import React, { useState, useEffect } from 'react';

const GroupButtonMaker = ({ selectedGroup}) => {
  const [newButtons, setNewButtons] = useState([]);
  console.log(newButtons);

  useEffect(() => {
    const createButtons = () => {
      setNewButtons(
        selectedGroup.map(item => {
          return (
            <button
              id={item.value}
              className={'btn green micro'}
              key={item.value}
              onClick={event => btnHandler(event)}
            >
              {item.label}
            </button>
          );
        })
      );
    };
    createButtons();
  }, [selectedGroup]);

  const btnHandler = event => {
//here at the handler I'm trying multiple different ways to find indexOf as a test. No luck so far.
    const eventID = event.currentTarget.id;
    let currentTargetIndex = newButtons
      .map(item => item.value)
      .indexOf(eventID);
    console.log(currentTargetIndex);
    console.log(newButtons.findIndex(x => x.value === eventID));
  };

  Array.prototype.indexOfObject = function arrayObjectIndexOf(property, value) {
    for (var i = 0, len = this.length; i < len; i++) {
      if (this[i][property] === value) return i;
    }
    return -1;
  };
// here i've hardcored one value as a test to see if it works but it didn't so far.
  console.log(newButtons.indexOfObject('value', 107));

  const idx = newButtons.reduce(function(cur, val, index, eventID) {
    if (val.value === eventID && cur === -1) {
      return index;
    }
    return cur;
  }, -1);
  console.log(idx);

  return <ul>{newButtons.map(item => item)}</ul>;
};
export default GroupButtonMaker;


预先感谢您对我当前问题的任何建议。希望我已经设法解决了这个问题。如果没有,请询​​问,我将尝试提供答案。

最佳答案

为什么不简单地将按钮的id传递给处理程序,而不是从event获取它。

您可以通过以下方式实现:onClick={(event) => btnHandler(item.value)}

然后在您的btnHandler中,只需从selectedGroup而不是newButtons查找所选按钮的索引。

在这里,尝试一下:

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

const GroupButtonMaker = ({ selectedGroup }) => {
  const [newButtons, setNewButtons] = useState([]);

  useEffect(() => {
    const buttons = selectedGroup.map(item => {
      return (
        <button
          id={item.value}
          className={"btn green micro"}
          key={item.value}
          onClick={(event) => btnHandler(item.value)}
        >
          {item.label}
        </button>
      );
    });
    setNewButtons(buttons);
  }, [selectedGroup]);

  const btnHandler = buttonId => {
    const selectedButtonIndex = selectedGroup.findIndex(item => item.value === buttonId);
    console.log("selectedButtonIndex is: ", selectedButtonIndex);
  };
  return <ul>{newButtons.map(item => item)}</ul>;
};
export default GroupButtonMaker;





  这是供您参考的Working Sample Code Demo

10-08 05:43
查看更多