[英]How can I add a click handler to BODY from within a React component?
I am building a pulldown menu React component that should close when the user clicks anywhere in the DOM outside of the component.我正在构建一个下拉菜单 React 组件,当用户单击组件外部DOM 中的任何位置时,该组件应该关闭。
Using jQuery I would typically add an event listener to the body
when the pulldown is opened, and remove it again when the pulldown is closed.使用 jQuery,我通常会在下拉菜单打开时向
body
添加一个事件侦听器,并在下拉菜单关闭时再次将其删除。 (The event listener itself closes the pulldown – any click events within the component are not propagated to prevent the body click handler from firing.) (事件侦听器本身关闭下拉菜单——组件内的任何点击事件都不会传播,以防止主体点击处理程序被触发。)
Is there any way to attach a listener to the body
element from within a React component?有没有办法从 React 组件中将侦听器附加到
body
元素? Or should I just use jQuery?还是我应该只使用 jQuery? (I'm a bit wary of mixing React and jQuery.)
(我有点担心混合 React 和 jQuery。)
React is just JavaScript so attaching a click handler to any element is done as normal by using addEventListener()
. React 只是 JavaScript,因此可以通过使用
addEventListener()
像往常一样将点击处理程序附加到任何元素。 Doing this in componentDidMount
is normally very nice and tidy and clean up after yourself in componentWillUnmount
by removing the added event handler.在
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>;
}
});
It's help who used function based components:使用基于函数的组件是有帮助的:
import React, { useEffect } from 'react';
const ZSideBar = (props) => {
useEffect(() => {
document.body.addEventListener('click', closeSidemenu );
return function cleanup() {
window.removeEventListener('click', closeSidemenu );
}
},[]);
let closeSidemenu = () => {
document.getElementById("sidebar-tree").style.left = "-310px";
}
return (
<div></div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.