[英]react: onClick - get only the clicked element, not the children
I have a button, inside this button is a fontawesome svg. 我有一个按钮,在此按钮内是一个非常棒的svg。 The listener is on the button only, not on the svg.
侦听器仅在按钮上,而不在svg上。 Though, when I click on the svg, the event.target is not the button.
但是,当我单击svg时,event.target不是按钮。
But I only need the button as target. 但是我只需要按钮作为目标。
Here's the code: 这是代码:
const icon = '<svg aria-hidden="true" data-prefix="fas" data-icon="paragraph" class="svg-inline--fa fa-paragraph fa-w-14 " role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M408 32H177.531C88.948 32 16.045 103.335 16 191.918 15.956 280.321 87.607 352 176 352v104c0 13.255 10.745 24 24 24h32c13.255 0 24-10.745 24-24V112h32v344c0 13.255 10.745 24 24 24h32c13.255 0 24-10.745 24-24V112h40c13.255 0 24-10.745 24-24V56c0-13.255-10.745-24-24-24z"></path></svg>';
class App extends React.Component {
constructor(props) {
super(props);
}
handleClick(event) {
event.stopPropagation();
console.log(event.target);
}
render() {
return (
<div>
<button onClick={this.handleClick}>
<span dangerouslySetInnerHTML={{__html: icon}} />
</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
I wrote a little pen: https://codepen.io/DaFunkyAlex/pen/aRvVjd 我写了一点笔: https : //codepen.io/DaFunkyAlex/pen/aRvVjd
You should use: event.currentTarget
, which is always the object listening for the event. 您应该使用:
event.currentTarget
,它始终是侦听事件的对象。
The event.target
is the actual target that received the click. event.target
是获得点击的实际目标。
It can be done in multiple ways. 它可以通过多种方式完成。 I prefer the CSS way of doing it, applying pointer-events : none to the children span .
我更喜欢CSS的方式,将指针事件应用到所有子元素span上 。
Codepen : https://codepen.io/imsontosh/pen/mzeqNx Codepen: https ://codepen.io/imsontosh/pen/mzeqNx
button {
background: #eee;
border: 1px solid #ddd;
width: 150px;
span{
pointer-events:none;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.