简体   繁体   中英

React onClick event on link

I have this weird thing i have this simple component

import React, {Component} from 'react';
const Logo = ({onClick}) => {
return (

    <a name="home" onClick={onClick} className="logo">

        <span className="logo-mini"></span>



    </a>

);
};


export default Logo;

the onClick event suppose to to get the click event on the link to get attribute name but what i got is undefined when i console.log the event.target the out put is <span class="logo-lg"></span>

in the root compenent my render methode call <Logo onClick={this.handleClick}/> handleClick method

    handleClick(){
    let to = event.target.name;
    console.log(event.target);
    }

You can access the desired attribute by chaining parentElement with the getAttribute() method. Try this in you handleClick method

console.log(event.target.parentElement.getAttribute('name'));

More info here:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute https://developer.mozilla.org/en/docs/Web/API/Node/parentElement


Alternatively, you could use:
console.log(event.target.getAttribute('name')); but this would require that you put the name attribute on your span element.

Also, in case the gist gets deleted, here is a full working code:

class Header extends React.Component { 
  handleClick(event) {
    console.log(event.target.parentElement.getAttribute('name'));
  }
  render() {
    return (
      <Logo onClick={this.handleClick}/>
    );
  }
}

const Logo = ({onClick}) => {
  return (
    <a name="home" onClick={onClick} className="logo">
        <span className="logo-mini">Logo</span>
    </a>
  );
};

ReactDOM.render(<Header/>, document.getElementById('app'));

Link to codepen: http://codepen.io/PiotrBerebecki/pen/LRRYRq

您需要将其绑定到函数调用。

 <Logo onClick={this.handleClick.bind(this)}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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