[英]Clicking Icon on Button Triggers Both onClicks (Button & Icon) in React
I have a Button
component ( bootstrap-react
) that has a X
icon on one end of the button.我有一个Button
组件 ( bootstrap-react
),在按钮的一端有一个X
图标。 Both the Button
and X
components have a onClick
handler defined. Button
和X
组件都定义了一个onClick
处理程序。
However, when a user clicks on the X
icon, both the onClick
functions of both components are triggered.但是,当用户点击X
图标时,两个组件的onClick
函数都会被触发。 How do we ensure that only the X
icon's onClick
is triggered when the icon is clicked?我们如何保证点击图标时只触发X
图标的onClick
呢?
import { Button } from 'react-bootstrap';
import { X } from 'react-bootstrap-icons';
function MyButton({onClick}) {
const handleRemoveClick = () => {
console.log('Clicked on icon')
}
return (
<Button variant="light" onClick={onClick}>
<span className="btn-text">Hello</span>
<X fill="#aaa" onClick={handleRemoveClick} />
</Button>
)
}
You can invoke stopPropagation on the event object when the X
button is clicked so that the event stops propagating.单击X
按钮时,您可以对事件 object 调用stopPropagation ,以便事件停止传播。
const handleRemoveClick = (e) => {
e.stopPropagation();
console.log('Clicked on icon')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.