Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React-什么是合成事件 #21

Open
PleaseStartYourPerformance opened this issue May 12, 2021 · 0 comments
Open

React-什么是合成事件 #21

PleaseStartYourPerformance opened this issue May 12, 2021 · 0 comments

Comments

@PleaseStartYourPerformance
Copy link
Owner

<div className="testDom" onClick={this.testDomClick()}><div>

React合成事件一套机制:React并不是将Click事件直接绑定在dom上面,而是采用事件冒泡的形式冒泡到document上面,然后React将事件封装给正式的函数处理运行和处理。

如果DOM上绑定了过多的事件处理函数,整个页面响应以及内存占用可能都会受到影响。React为了避免这类DOM事件滥用,同时屏蔽底层不同浏览器之间的事件系统差异,实现了一个中间层——SyntheticEvent。

  1. 当用户在为onClick添加函数时,React并没有将Click时间绑定在DOM上面。
  2. 而是在document处监听所有支持的事件,当事件发生并冒泡至document处时,React将事件内容封装交给中间层SyntheticEvent(负责所有事件合成)
  3. 所以当事件触发的时候,对使用统一的分发函数dispatchEvent将指定函数执行。

以下代码来显示两者的区别

class Test extends Component {
    constructor() {
        super(arguments);
        this.onReactClick.bind(this);
    }
    componentDidMount() {
        const parentDom = ReactDOM.findDOMNode(this);
        const childrenDom = parentDom.queneSelector(".button");
        childrenDom .addEventListen('click', this.onDomClick, false);
    }
    onDomClick() {  // 事件委托
        console.log('Javascript Dom click');
    }
    onReactClick() {  // react合成事件
        console.log('React click');
    }
    render() {
        <div>
            <button className="button" onClick={this.onReactClick()}>点击</button>
        </div>
    }
}

输出
Javascript Dom click
React click

可以看待原生绑定快于合成事件绑定

相关连接:https://www.jianshu.com/p/8d8f9aa4b033

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant