材质UI IconButton onClick不允许处理事件

时间:2020-02-14 02:23:54

标签: material-ui iconbutton

我安装了“ @ material-ui / core”:“ ^ 4.9.2”和“ @ material-ui / icons”:“ ^ 4.9.1”。

在我的表单中,我有几行,每行都有一个添加按钮和一个删除按钮。我希望使用“删除”按钮删除单击的行。它与带有“-”字符的常规Button一起使用时效果很好。但是我想让它看起来很漂亮,所以我从IconButton替换了Button,并导入了要使用的图标

import {AddCircleOutline,RemoveCircleOutlineOutlined} from "@material-ui/icons";

我的IconButton看起来像这样:

        <IconButton
          onClick={props.onRemoveClick}
          className="align-self-center"
          color="info"
          size="sm"
          disabled={props.index > 0 ? false : true}
          <RemoveCircleOutlineOutlined/>
        </IconButton>

单击IconButton时,将调用onClick方法(由于控制台中的日志,我知道了),但由于该事件现在未定义,因此我无法处理该事件。

有趣的是,如果我单击与图标不对应的按钮区域,它将起作用。但是显然,我需要它在按钮的整个区域中起作用。

enter image description here

这不是绑定问题,因为我已经对其进行了测试。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

文档中未引用的道具将继承到其内部<EnhancedButton />,因此您需要使用包装器。

      <IconButton
          onClick={(e) => props.onRemoveClick(e)}
          className="align-self-center"
          color="info"
          size="sm"
          disabled={props.index > 0 ? false : true}
          <RemoveCircleOutlineOutlined/>
        </IconButton>

答案 1 :(得分:0)

好吧,你给个主意。由于我需要一个索引来标识该行的按钮,因此我通过onClick方法的参数将索引发送给了它,如下所示:

onClick={e => props.onRemoveClick(props.index)}

通过这种方式,我不需要处理事件。我还必须将我的方法绑定到构造函数上:

constructor(props) { super(props); this.handleRemoveClick = this.handleRemoveClick.bind(this); }

现在我有了想要的行为

答案 2 :(得分:0)

您可以看到github使用here。打字稿定义文件存在一些问题,但我们可以解决它。

解决方案

我试图像github问题中那样解决它,但是没有用。所以这对我有用。

const onClick = (e: any) => {
    // e is of type any so the compiler won't yell at you

}
<IconButton onClick={(e) => onClick(e)}>