美文网首页
React的合成事件

React的合成事件

作者: 沉默紀哖呮肯伱酔 | 来源:发表于2021-12-06 20:21 被阅读0次

    React的合成事件:
    React中声明的事件最终只绑定在document节点上, 通过事件代理的方式来实现事件的操作,从而减少了内存的消耗。我们来看一下下面的实例的执行结果

    import React from "react";
    import ReactDOM from "react-dom";
    export class Demo extends React.Component {
        componentDidMount() {
            const parentDom = ReactDOM.findDOMNode(this)
            const childDom = parentDom.querySelector('.child')
            parentDom.addEventListener('click', this.onParentDomClick, false)
            childDom.addEventListener('click', this.onChildDomClick, false)
        }
    
        onParentDomClick = e => {
            console.log('dom event parent')
        }
        
        onChildDomClick = e => {
            console.log('dom event child')
        }    
        
        onParentClick = e => {
            console.log('react event parent')
        }
    
        onChildClick = e => {
            console.log('react event child')
        }
    
        render() {
            return (
                <div onClick={this.onParentClick}>
                    <div className="child" onClick={this.onChildClick}>on Click</div>
                </div>
            )
        }
    }
    

    当我们点击子DOM元素的时候, 执行结果

    dom event child 
    dom event parent 
    react event child 
    react event parent 
    

    通过输出结果, 我们可以知道先触发的是DOM的原生事件, 之后才去执行React的合成事件。

    import React from "react";
    import ReactDOM from "react-dom";
    export class Demo extends React.Component {
        componentDidMount() {
            const parentDom = ReactDOM.findDOMNode(this)
            const childDom = parentDom.querySelector('.child')
            parentDom.addEventListener('click', this.onParentDomClick, false)
            childDom.addEventListener('click', this.onChildDomClick, false)
        }
    
        onParentDomClick = e => {
            console.log('dom event parent')
        }
        
        onChildDomClick = e => {
            console.log('dom event child')
        }    
        
        onParentClick = e => {
            console.log('react event parent')
        }
    
        onChildClick = e => {
            e.stopPropagation();
            console.log('react event child')
        }
    
        render() {
            return (
                <div onClick={this.onParentClick}>
                    <div className="child" onClick={this.onChildClick}>on Click</div>
                </div>
            )
        }
    }
    

    我们修改一下代码,阻止Child的冒泡事件看一下执行的结果:

    dom event child 
    dom event parent 
    react event child 
    

    当我们给子元素添加阻止冒泡事件的处理的时候,React的事件并不能传递给父级组件,而原生事件则不受任何影响。

    结论: React的合成事件是通过代理的方式来处理的。

    相关文章

      网友评论

          本文标题:React的合成事件

          本文链接:https://www.haomeiwen.com/subject/tjfpzltx.html