底层原理
useClickAway 监听目标元素外的点击事件
核心底层原理是在 document 上绑定了一个冒泡事件。当事件冒泡到 document 时.会判断事件目标元素是否为传入的 ref 下的子元素调用了 useClickAway。
https://zhuanlan.zhihu.com/p/530590692
实现点击搜索图标出来搜索框,点击其他部分,隐藏搜索框
import { Input } from 'antd';
import { useClickAway } from "ahooks"
import { SearchOutlined } from '@ant-design/icons'
import { useRef, useState } from 'react';
// 搜索组件
const [searchInputVisible, setSearchInputVisible] = useState<boolean>(false);
const searchWrapperRef = useRef(null);
useClickAway(() => {
setSearchInputVisible(false)
}, searchWrapperRef);
return (
<div onClick={(e) => e.stopPropagation()}>
{
searchInputVisible
?
(<div ref={searchWrapperRef} >
<Input.Search allowClear autoFocus onSearch={(val) => console.log(val)} style={{ width: '120px' }} />
</div>)
:
(<SearchOutlined onClick={() => setSearchInputVisible(true)} />)
}
</div>
)
效果图
点击空白部分消失