检索单击了哪个按钮React/Material [英] Retrieve which button was clicked React/Material

查看:51
本文介绍了检索单击了哪个按钮React/Material的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个动态生成的材质UI按钮,当用户单击其中的任何一个时,我想知道单击了哪个(例如,获取我在下面分配的 name 属性的值).如何解决呢?基本上,我想检索单击的按钮的某些属性.这是一些代码

I have several dynamically generated material UI buttons, and when user clicks any of them I would like to know which was clicked (let's say obtain the value of name attribute which I assigned below). How can this be solved? Basically I want to retrieve some attribute of the button which was clicked. Here is some code

    {
      that.state.items.map(function (item) {
        return (
          <div key={item.id}>
            <FlatButton
              label={item.regionName}
              name={item.id}
              primary={true}
              onClick={that.handleRegionClick}
            ></FlatButton>
          </div>
        );
      });
    }
    
    handleRegionClick(e);
    {
      console.log(e.target.name); // This prints undefined
      // If I could get here the _item.id_ which I assigned to _name_ I would be fine.
    }

PS.我在构造函数中也有这个

PS. I also have this in constructor

 this.handleRegionClick = this.handleRegionClick.bind(this);

推荐答案

您可以做一件事,而不是将ID分配给名称,而是使用 onClick 将该ID绑定 bind 处理函数.每当单击任何按钮时,它都会将该ID传递给处理函数.

You can do one thing, instead of assigning the id to name, bind that id with onClick handler function. Whenever any of the button will be clicked, it will pass that id to handler function.

赞:

let a = [{ id: 1 }, { id: 2 }, { id: 3 }];

a.map(item => {

   return <FlatButton
    label={item.regionName}
    primary={true}
    onClick={() => this.handleRegionClick(item.id)} />

})

handleRegionClick 函数:

handleRegionClick(id){
  console.log(id);
}

注意:这里不需要绑定 handleRegionClick ,因为在这里,我们将 arrow函数与onClick一起使用,并调用 handleRegionClick .

Note: binding of handleRegionClick is not required here because here, we are using arrow function with onClick and calling handleRegionClick normally.

这篇关于检索单击了哪个按钮React/Material的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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