简体   繁体   English

如何在 onClick 中获取 Material-UI Button 属性?

[英]How to get Material-UI Button attribute in onClick?

How to get the attribute of Material-UI Button?.如何获取 Material-UI Button 的属性? I've tried the getAttribute() but it gives me null .我试过getAttribute()但它给了我null I know this is possible using normal <button> tags but I want to try using Material-UI button.我知道这可以使用普通的<button>标签,但我想尝试使用 Material-UI 按钮。

My button-我的按钮-

<Button 
    variant="outlined" 
    id={button1} 
    button-key="buttonAttribute"
    onClick={this.isClicked}>
    MyButton
</Button>

click function -点击功能——

isClicked = (e) => {
   const attButton = e.target.getAttribute('button-key')
   console.log(attButton)
}

My console returns null .我的控制台返回null How can it return buttonAttribute它如何返回buttonAttribute

Try using currentTarget instead尝试改用currentTarget

e.currentTarget.getAttribute("button-key")

You can also use data attributes by prefixing your attribute name with data-* .您还可以通过在属性名称前加上data-*来使用数据属性 It's a good practice to use this instead because it creates a ' namespace ' for your custom attribute so they won't clash with the standard HTML attributes.改用它是一个好习惯,因为它会为您的自定义属性创建一个“命名空间”,因此它们不会与标准 HTML 属性发生冲突。

<Button
  onClick={(e) => {
    console.log(e.currentTarget.dataset.buttonKey);
  }}
  data-button-key="buttonAttribute"
>

Live Demo现场演示

编辑 64305609/how-to-get-material-ui-button-attribute-in-onclick

它显示为null ,因为如果您记录e.target ,那么您将看到按钮组件中存在的span元素,并且您将 id 传递给它的根元素,即div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM