Let’s go straight to the code. I’ve been thinking about it for a long time and don’t know where the problem is.
state = {
spread: false
}
componentDidMount() {
console.log('document clicked')
document.onclick = () => {
if(this.state.spread) {
this.setState({
spread: false
})
}
}
}
spreadHandler (e) {
console.log('target clicked')
// 这个事件绑定在一个 a 标签上
e.stopPropagation()
this.setState({
spread: !this.state.spread
})
}
This function is similar to the navigation bar at the top of Taobao, except that I use click events here. Now I cancel the bubbling when I trigger the spreadHandler, but the click event of the document will still be triggered. I don’t know if it’s because the event is bound to the a tag, or if it’s caused by some other reason. Does anyone know what’s going on?
Preventing bubbling in react's synthetic events cannot cancel the bubbling of native events.
Preventing bubbling in native events can prevent bubbling in react's synthetic events.
So you should try to avoid mixing them, and it must be used If so, you can add a layer of judgment in the document event handler.
e.preventDeafult()
Try this:
React’s event mechanism is different from that of native js.
React’s synthetic events are all implemented through the event proxy bound to the click on the document, so it is impossible to prevent other event processing on the docuemnt by preventing synthetic events from bubbling (already bubbled to the document), so you have to use native Event