如何获得被点击的按钮的ID?ReactJS [英] How do I get the id of a button that was clicked? ReactJS

查看:150
本文介绍了如何获得被点击的按钮的ID?ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何获取被单击的按钮的ID(因为它是未知的).因此,当单击按钮时,我知道该特定按钮的ID是什么.页面上有很多按钮,我想知道按下了哪个按钮(它们都有唯一的ID).当前的按钮如下所示:

I was wondering how I would go about getting the id (becuase it is unknown) of a button that is clicked. So when the button is clicked, I know what the id of that specific button is. There are lots of buttons on the page and I would like to know which button is pressed (they all have unique id's). Currently the buttons look like this:

  <button key={uuidv4()} id={this.props.keyword} value={this.props.keyword} onClick={this.props.onClick} className="removeButton">Remove</button>

推荐答案

您可以使用 event.target.id 来获取单击按钮的ID

You can use event.target.id to get the ID of button clicked

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(event) {
    const id = event.target.id;
    console.log(id);
  }
  render() {
    return (
      <button id="unique-id" onClick={this.handleClick}>Button</button>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

这篇关于如何获得被点击的按钮的ID?ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆