How to return an attribute of clicked element in react?

蓝咒 提交于 2021-01-28 14:35:43

问题


I was wondering if there is a simple way to get an attribute of clicked element in React.js:

function App () {
    return (
        <button
          title={'foo'}
          onClick={myFunction(this)}
         >
            click me
         </button>
    )
}

function myFunction(e) {
  alert(e.getAttribute('title')); 
}

Right now I'm getting: TypeError: can't access property "getAttribute", e is undefined.

I need it inside a function for pass the attribute into another (working) function later on.


回答1:


You can access the title via currentTarget

try this:


function App () {
    return (
        <button
          title={'foo'}
          onClick={myFunction}
         >
            click me
         </button>
    )
}

function myFunction(e) {
  alert(e.currentTarget.title); 
}




回答2:


You have to call like this

<button
    title={'foo'}
    onClick={(e) => myFunction(e.currentTarget.title)}
>
   click me
</button>

In the function, you have to get like this.

function myFunction(e) {
  alert(e); // e is the value that you have pass 
}



回答3:


onClick={myFunction(this)} means that the value of onClick prop will be set to the value that is returned by myFunction, i.e. myFunction(this) is run immediately when the code is evaluated (and not when the button is clicked). You probably want to have something like onClick={() => myFunction(this)} instead, so that the arrow function will be run when the button is clicked (and the arrow function will call myFunction).

However, this is undefined, as seen from the error message you got ("e is undefined"), hence you get the error (undefined doesn't have a property called "getAttribute").

You can pass the event object to myFunction like this:

onClick={(e) => myFunction(e)}

Then you can access the button element with e.currentTarget and then get the title attribute:

function myFunction(e) {
  alert(e.currentTarget.getAttribute('title')); 
}


来源:https://stackoverflow.com/questions/62743418/how-to-return-an-attribute-of-clicked-element-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!