简体   繁体   English

如何确保 material-ui 中的整个 Button 组件为 onClick 事件返回相同的 ID 值?

[英]How to ensure entire Button component in material-ui returns the same ID value for an onClick event?

When attempting to console log the ID of the Button component, the ID is only correctly logged when pressing the edges of the button (outside of the class that contains the button label).尝试控制台记录 Button 组件的 ID 时,只有在按下按钮边缘(包含按钮标签的 class 之外)时才会正确记录 ID。 This problem doesn't occur on a normal js button where the text is included in the component.在文本包含在组件中的普通 js 按钮上不会出现此问题。 How do I ensure the proper ID value is returned for the whole Button component?如何确保为整个 Button 组件返回正确的 ID 值?

Button Component and onClick implementation:按钮组件和 onClick 实现:

<Button
  onClick={(e) => handleInput(e, "value")}
  value={"Grocery Store Workers"} 
  size="small"
  color="primary"
>
  Select
</Button>
const handleInput = (e) => {
  e.preventDefault();
  console.log(e.target.value)
  setCardSelected(e.target.value);
}

Implementation working with normal button:使用普通按钮的实现:

<button
  onClick={(e) => handleInput(e, "value")} 
  value={"Grocery Store Workers"} 
  size="small"
  color="primary"
>
  Select
</button>

Console when clicking button center vs clicking button edge单击按钮中心与单击按钮边缘时的控制台

单击按钮中心与单击按钮边缘时的控制台

Button edge (green) vs button span text (blue)按钮边缘(绿色)与按钮跨度文本(蓝色)

按钮边缘(绿色)与按钮跨度文本(蓝色)

Ah, I see the issue here.啊,我看到了这里的问题。 The solution is to reference to currentTarget.id rather than target.value from the synthetic event (e).解决方案是从合成事件 (e) 中引用 currentTarget.id 而不是 target.value。 This works on the whole button because:这适用于整个按钮,因为:

  • target is the element that triggered the event (eg, the user clicked on) target 是触发事件的元素(例如,用户点击)
  • currentTarget is the element that the event listener is attached to. currentTarget 是事件侦听器附加到的元素。

You can try to add a data-index attribute to your component and get it back using getAttribute method.您可以尝试向组件添加data-index属性并使用getAttribute方法将其取回。

<Button
  onClick={(e) => handleInput(e, "value")}
  value={"Grocery Store Workers"} 
  size="small"
  color="primary"
  data-index={//your id}
>
  Select
</Button>
const handleInput = (e) => {
  e.preventDefault();
  console.log(e.currentTarget.getAttribute('data-index'))
  setCardSelected(e.currentTarget.getAttribute('data-index'));
}

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

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