最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React onClick event on link - Stack Overflow

programmeradmin9浏览0评论

I have this weird thing i have this simple ponent

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 penent my render methode call <Logo onClick={this.handleClick}/> handleClick method

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

I have this weird thing i have this simple ponent

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 penent my render methode call <Logo onClick={this.handleClick}/> handleClick method

    handleClick(){
    let to = event.target.name;
    console.log(event.target);
    }
Share Improve this question asked Sep 18, 2016 at 15:16 AmineAmine 1722 gold badges3 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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/en-US/docs/Web/API/Element/getAttribute https://developer.mozilla/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

You need to bind this to your function call.

 <Logo onClick={this.handleClick.bind(this)}/>
发布评论

评论列表(0)

  1. 暂无评论