我有几个动态生成的 Material UI 按钮,当用户单击其中任何一个时,我想知道单击了哪个(假设获取我在下面指定的 name
属性的值)。
如何解决?基本上我想检索被点击的按钮的一些属性。
这是一些代码
{
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.
}
附言。我在构造函数中也有这个
this.handleRegionClick = this.handleRegionClick.bind(this);
最佳答案
你可以做一件事,而不是将 id 分配给 name,bind
该 id 与 onClick
处理函数。每当单击任何按钮时,它都会将该 ID 传递给处理函数。
像这样:
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
的绑定(bind)在这里不是必需的,因为在这里,我们使用带有onClick 的arrow function
并调用handleRegionClick
正常。
关于javascript - 检索在 React 中单击了哪个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43604167/