javascript 如何从 React 组件中向 BODY 添加点击处理程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32485520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:21:27  来源:igfitidea点击:

How can I add a click handler to BODY from within a React component?

javascriptjqueryreactjs

提问by Tim

I am building a pulldown menu React component that should close when the user clicks anywhere in the DOM outsideof the component.

我正在构建一个下拉菜单 React 组件,当用户单击组件外部DOM中的任何位置时,该组件应该关闭。

Using jQuery I would typically add an event listener to the bodywhen the pulldown is opened, and remove it again when the pulldown is closed. (The event listener itself closes the pulldown – any click events withinthe component are not propagated to prevent the body click handler from firing.)

使用 jQuery,我通常会body在下拉菜单打开时添加一个事件侦听器,并在下拉菜单关闭时再次将其删除。(事件侦听器本身会关闭下拉菜单——组件的任何点击事件都不会传播,以防止主体点击处理程序被触发。)

Is there any way to attach a listener to the bodyelement from within a React component? Or should I just use jQuery? (I'm a bit wary of mixing React and jQuery.)

有没有办法body从 React 组件中将侦听器附加到元素?还是我应该只使用 jQuery?(我有点担心混合 React 和 jQuery。)

回答by Henrik Andersson

React is just JavaScript so attaching a click handler to any element is done as normal by using addEventListener(). Doing this in componentDidMountis normally very nice and tidy and clean up after yourself in componentWillUnmountby removing the added event handler.

React 只是 JavaScript,因此通过使用addEventListener(). 通过删除添加的事件处理程序,这样做componentDidMount通常非常好和整洁,并在自己进入后进行清理componentWillUnmount

var Component = React.createClass({
    componentDidMount: function () {
        document.body.addEventListener('click', this.myHandler);
    },
    componentWillUnmount: function () {
        document.body.removeEventListener('click', this.myHandler);
    },
    myHandler: function () {
        alert('click');
    },
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});