简体   繁体   English

如何将指定 onClick 的确切元素作为 e.target 获取?

[英]How to get as e.target the exact element at which onClick is specified?

I have a React Component and give it onClick event handler:我有一个 React 组件并给它onClick事件处理程序:

function Item(props) {
  return <li onClick={props.onClick}>{props.children}</li>
}

Then I use the Component like this:然后我像这样使用组件:

<Item onClick={ function(e) {console.log(e.target)} }>
  <span>This element is returned as e.target if clicked on it!</span>
</Item>

When I click on the text, the span element is logged as target and when it is clicked outside given span, li element is logged as target.当我点击文本时, span元素被记录为目标,当它在给定的跨度之外被点击时, li元素被记录为目标。

The problem is:问题是:
If there is a lot of child elements inside li element, and id or name are have to be gotten, it becomes a "hacky" task...如果li元素内部有很多子元素,并且必须获取 id 或 name,这将成为一项“hacky”任务......

The question is:问题是:
Is it possible to get inside a handler function as e.target the exact element at which onClick is specified (not it's children; in this case li )?是否有可能得到一个处理函数作为e.target在其确切的元素中onClick指定(不是的孩子,在这种情况下,)?

PS.附注。 No jQuery for solution if possible.如果可能,没有 jQuery 解决方案。

event.target will always give you the element, which dispatched the event. event.target将始终为您提供调度事件的元素。 In order to get the element who's listener is currently processed, you have to use event.currentTarget .为了获取当前正在处理侦听器的元素,您必须使用event.currentTarget

This should help: https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets这应该会有所帮助: https : //developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets

Here is a simple example to illustrated your issue:这是一个简单的例子来说明你的问题:

 const Inner = () => <div className="inner">Inner</div> const Outer = () => { const clickHandler = e => { console.log('target:', e.target.getAttribute('class')); console.log('currentTarget:', e.currentTarget.getAttribute('class')); }; return (<div className="outer" onClick={clickHandler}><Inner /></div>); }; ReactDOM.render(<Outer/>, document.getElementById('app'));
 .outer { background: rosybrown; padding: 40px; } .inner { background: cornsilk; padding: 20px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>

Yes是的

 const { render } = ReactDOM; function Item(props) { return <li onClick={props.onClick} {props.children} </li> } render( <Item onClick = { function(e) { console.log(e.currentTarget) } }> <span> This element is returned as e.target if clicked on it! </span> </Item>, document.getElementById('root') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>

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

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