import React, { useState, useEffect, useRef, forwardRef, ForwardedRef } from 'react';
interface BProps {
// B元素的其他属性
}
const B = forwardRef((props: BProps, ref: ForwardedRef<HTMLDivElement>) => {
return (
<div ref={ref}>
{/* B元素的内容 */}
</div>
);
});
function App(): JSX.Element {
const [showB, setShowB] = useState<boolean>(false);
const bRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (bRef.current && !bRef.current.contains(event.target as Node)) {
setShowB(false);
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
return (
<div>
<a href="#" onClick={() => setShowB(!showB)}>点击显示/隐藏</a>
{showB && (
<B ref={bRef} />
)}
</div>
);
}
export default App;
非TS
import React, { useState, useEffect, useRef } from 'react';
function App() {
const [showB, setShowB] = useState(false);
const bRef = useRef(null);
useEffect(() => {
function handleClickOutside(event) {
if (bRef.current && !bRef.current.contains(event.target)) {
setShowB(false);
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
return (
<div>
<a href="#" onClick={() => setShowB(!showB)}>点击显示/隐藏</a>
{showB && (
<div ref={bRef}>
{/* B元素的内容 */}
</div>
)}
</div>
);
}
export default App;
评论区