简体   繁体   English

React Button 元素 id 给出空字符串

[英]React Button element id giving empty string

I want to pass the id of my Button in my function call when the button is clicked.单击按钮时,我想在 function 调用中传递我的 Button 的 ID。 But How to do that?但是怎么做呢? I read the available solutions but nothing helped me.我阅读了可用的解决方案,但没有任何帮助。

Problem: The below code prints an empty string in the console问题:下面的代码在控制台中打印一个空字符串

Expectation: paras123 should get printed期望: paras123 应该被打印出来

<TableCell align="center">
   <Button id="paras123" onClick={(e)=>console.log(e.target.id)}>
      Pre-Session Form
   </Button>
 </TableCell>

Because target is the span show text Pre-Session Form .因为target是跨度显示文本Pre-Session Form You need use currentTarget to get button id:您需要使用 currentTarget 来获取按钮 id:

onClick={(e) => console.log(e.currentTarget.id)}

Check the target value: console.log(e.target) .检查targetconsole.log(e.target) It will response following like that它会像这样响应

<span class="MuiButton-label">Pre-Session Form</span>

There is no id value.没有id值。 If your idea is to print paras123 , check this example link.如果您的想法是打印paras123 ,请查看此示例链接。

https://codesandbox.io/s/damp-paper-ftumv?file=/src/App.js:1592-1595

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

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