【问题标题】:Retrieve which button was clicked in React检索在 React 中单击了哪个按钮
【发布时间】:2017-04-25 07:23:14
【问题描述】:

我有几个动态生成的材质 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);

【问题讨论】:

  • 一个问题,如何在任何循环中动态生成按钮?
  • @MayankShukla 在地图中是的

标签: javascript reactjs material-ui


【解决方案1】:

您可以做一件事,而不是将 id 分配给名称,bind 使用 onClick 处理函数的那个​​ id。每当单击任何按钮时,它都会将该 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,因为这里我们使用arrow function和onClick并正常调用handleRegionClick

【讨论】:

  • 这有效:onClick={() => that.handleRegionClick(item.id)} (在我的情况下使用它而不是这个渲染)
【解决方案2】:

我觉得你的问题很奇怪。你可以简单地做到这一点。

<FlatButton label={item.regionName} name={item.id} primary={true} onClick={that.handleRegionClick.bind(this, item.id)}></FlatButton>

handleRegionClick(itemId){
  console.log(itemId)
}

【讨论】:

    【解决方案3】:

    不要为此使用onClick。相反,当您生成按钮时,添加一个事件侦听器。如果你这样做,那么你可以通过e.toElement 访问被点击的元素,并通过e.toElement.name 访问它的name 属性(好像你的item.id 在name 属性中)。

    for (...) { // however many buttons you generate
        var x = generateButtonSomehow(); // make sure it returns the DOM element
        x.addEventListener('click', function(e) {
            console.log(e.toElement.name);
        });
    }
    

    【讨论】:

      【解决方案4】:

      也许试图将 that.handleRegionClick() 绑定到这个?

      that.handleRegionClick.bind(that)

      那么你应该可以访问e.target

      【讨论】:

      • e.target 给了我表单...而不是被点击的按钮。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 2017-03-28
      • 2014-10-09
      • 1970-01-01
      相关资源
      最近更新 更多