简体   繁体   English

如何在 ReactJs 中的 map 函数中使用 OnClick 获取 DOM 元素 ID

[英]How to get DOM element id with OnClick inside map fuction in ReactJs

I'm trying to get the DOM element id to change the background of a <td> .我正在尝试获取 DOM 元素 id 来更改<td>的背景。 I'm printing a calendar with a map function from an array called from an outer function and adding an onclick function to each loop. I'm printing a calendar with a map function from an array called from an outer function and adding an onclick function to each loop. But when I click the <td> I get the last id from that row.但是,当我单击<td>时,我会从该行获得最后一个 id。 In the alert function, I get the value of the last day from the row在警报 function 中,我从行中获取了最后一天的值

Any suggestions?有什么建议么?

Calendar Example This is my code:日历示例这是我的代码:

cols = new Array(7).fill(0).map((zero, arrayCounter) => {
  if ((i === 0 && arrayCounter < weekDay) || numberDays < counterDay + 1) {
    return (
      <td id={arrayCounter} key={arrayCounter}>
        &nbsp;
      </td>
    );
  } else {
    return (
      counterDay++,
      (
        <td
          id={this.state.month + counterDay}
          key={this.state.month + counterDay}
          onClick={() => this.handleDays(actualRow, counterDay)}
        >
          {counterDay}
        </td>
      )
    );
  }
});

// When press a day
handleDays = (actualRow, counterDay) => {
  alert(actualRow + "-" + counterDay);
};

I think your problem is that actualRow and counterDay variables are not saved for every individual row, they are pointing to the cycle variables and at the end of cycle they will always be equal to the values of last cycle.我认为您的问题是, actualRowcounterDay变量并没有为每一行保存,它们指向循环变量,并且在循环结束时它们将始终等于上一个循环的值。

What you can do is save values for every row in closure.您可以做的是保存关闭中每一行的值。

For example, you can rewrite your handleDays function to something like例如,您可以将您的handleDays function 重写为类似

handleDays = (actualRow, counterDay) => () => {
  alert(actualRow + "-" + counterDay);
};

And call us it in the <td /> like并在<td />中称我们为


<td
  id={this.state.month + counterDay}
  key={this.state.month + counterDay}
  onClick={this.handleDays(actualRow, counterDay)}
>
    {counterDay}
</td>

So, this construction will call handleDays with actualRow and counterDay variables on every cycle and return new function with variables saved in the closure.因此,此构造将在每个循环中调用带有handleDayscounterDay变量的actualRow并返回新的 function 并将变量保存在闭包中。

You can read how the closer works in details here https://javascript.info/closure您可以在此处详细了解关闭器的工作原理https://javascript.info/closure

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

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