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

javascript - React event.target is not the element I set event Listener on - Stack Overflow

programmeradmin5浏览0评论

const onClick = (e) => {
  console.log(e.target);
}
const App = () => (
  <button
    name={'YES'}
    className="btn waves-effect waves-light left blue darken-4"
    onClick={onClick}
  >
    Yes
    <i className='material-icons left'>done</i>
  </button>
);

ReactDOM.render(<App />, document.querySelector("#app"));
<script src=".14.8/react.min.js"></script>
<script src=".14.8/react-dom.min.js"></script>
<div id="app">

const onClick = (e) => {
  console.log(e.target);
}
const App = () => (
  <button
    name={'YES'}
    className="btn waves-effect waves-light left blue darken-4"
    onClick={onClick}
  >
    Yes
    <i className='material-icons left'>done</i>
  </button>
);

ReactDOM.render(<App />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app">

I need e.target to be <button> in all possible cases, but when I click on <i>(or any other element as it seems), the target is <i> respectively. Its probably not error, but i don't know what to do about it.

Share Improve this question edited Mar 6, 2017 at 20:04 Piliponful asked Mar 6, 2017 at 19:52 PiliponfulPiliponful 1243 silver badges10 bronze badges 1
  • This is known as event bubbling. stackoverflow./questions/4616694/…. In order to help you here we would need to know why you want the target to be button, not how to do it. – azium Commented Mar 6, 2017 at 19:57
Add a ment  | 

1 Answer 1

Reset to default 17

Use event.currentTarget, which will always be the element on which the handler was added. event.target will always be the element on which the event occurred.

<button
  name={answerTypes.YES}
  className="btn waves-effect waves-light left blue darken-4"
  onClick={this.onClick}
>
  Yes
  <i className='material-icons left'>done</i>
</button>

onClick(e) {
  console.log(e.currentTarget);
}
发布评论

评论列表(0)

  1. 暂无评论