赞
踩
步骤一:通过React.useRef()获取指定元素;
步骤二:给document对象添加点击事件;
步骤三:通过ref.current.contains()函数判断点击的元素是否是当前元素;
步骤四:如果不是当前元素(非指定元素)则执行想要的事件;
- const Box = (props: any) => {
- const ref = useRef(null);
-
- const handleClickOutside = (event) => {
- if (!ref.current) return;
- if (!ref?.current?.contains?.(event.target)) {
- // 在这里执行你需要的操作
- console.log('你没有点击Box');
- } else {
- console.log('你点击了Box');
- }
- };
-
- useEffect(() => {
- // 添加事件监听器到document
- document.addEventListener('click', handleClickOutside, true);
- return () => {
- // 组件卸载时移除监听器
- document.removeEventListener('click', handleClickOutside, true);
- };
- }, []);
-
- return (
- <div ref={ref}>
- 指定元素
- </div>
- );
- };
-
- export default Box;

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。