如何获得e.target指定onClick的确切元素?

ole*_*mal 3 javascript events children javascript-events reactjs

我有一个React组件并给它onClick事件处理程序:

function Item(props) {
  return <li onClick={props.onClick}>{props.children}</li>
}
Run Code Online (Sandbox Code Playgroud)

然后我像这样使用Component:

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

单击文本时,span元素将记录为目标,当在给定范围外单击时,li元素将记录为目标.

问题是:如果li元素中有很多子元素,并且必须得到id或name,它就变成了"hacky"任务......

问题是:是否有可能将处理函数作为e.target放入指定onClick的确切元素(不是它的子节点;在本例中为li)?

PS.如果可能的话,没有jQuery解决方案.

Seb*_*ald 10

event.target将始终为您提供派遣事件的元素.为了获得当前正在处理侦听器的元素,您必须使用event.currentTarget.

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

这是一个简单的例子来说明你的问题:

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'));
Run Code Online (Sandbox Code Playgroud)
.outer {
  background: rosybrown;
  padding: 40px;
}

.inner {
  background: cornsilk;
  padding: 20px;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)