javascript - Binding events and preventing event bubbling in react
学习ing
学习ing 2017-06-26 10:57:42
0
4
861

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?

学习ing
学习ing

reply all(4)
滿天的星座

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.

document.addEventListener('click', function(e){
    // 类似事件委托, 判断一下发生事件的元素.
    if( e.target.nodeName.toLowerCase() === 'a' ) {
        return;
    }
}, false);
学习ing

e.preventDeafult()

代言

Try this:

e.nativeEvent.stopImmediatePropagation();

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template