Material UI IconButton onClick 不允许处理事件

Material UI IconButton onClick doesn't let to handle event

我安装了 "@material-ui/core": "^4.9.2" 和 "@material-ui/icons": "^4.9.1".

在我的表单中有几行,每一行都有一个添加按钮和一个删除按钮。我希望删除按钮从中删除被单击的行。它适用于带有“-”字符的常规按钮。但我想要它很花哨,所以我用 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 方法(我知道是因为我的控制台中有日志)但我无法处理该事件,因为它现在未定义。

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

这不是一个有约束力的问题,因为我已经测试过了。

有什么想法吗?

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

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

好吧,你提出了一个想法。因为我需要一个索引来标识行的按钮,所以我通过 onClick 方法的参数发送了索引,如下所示:

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

这样我就不需要处理事件了。我还必须在构造函数上绑定我的方法:

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

现在我得到了想要的行为

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

解决方案

我尝试像 github 问题一样解决它,但没有成功。所以这对我有用。

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

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

我不知道原因,但使用 e.currentTarget 帮助我获得了我想要的按钮,而不是其中的 material 图标。

onClick={(e) => {
    return console.log(e.currentTarget)
}}