我需要檢查用戶是在某個區域的內部還是外部點擊。詳細地說,我需要知道我是否點擊了一個react-select或任何其他組件。我發現我可以通過以下方式做到這一點:
if (typeof window !== 'undefined') {
window.addEventListener('click', function (e: any) {
const boxId = e.target?.id;
if (boxId === labelId) {
//isClicking inside the box
setIsFocusing(true);
} else {
//isClicking outside the box
setIsFocusing(false);
}
});
}
boxId 包含您單擊的組件的ID。所以這可能是解決方案。
我的實際問題是,react-select即使官方檔案說您可以通過經典方式,顯然我也無法為組件設定 Id ,這意味著將 id 屬性提供給組件。
在這個沙箱中,我做了兩個例子。一種帶有基本的 select,一種帶有react-select。基本的作業方式應該如何。我點擊一個標簽,選擇出現,然后你可以選擇。當您單擊外部時,它會消失并可視化標簽。不能用 react-select 做到這一點,因為我無法為其設定 ID。
實際上不能這樣做,onClick或者onFocus因為我無法檢查我是否在外面點擊。
你覺得我能怎么解決這個問題?
uj5u.com熱心網友回復:
您可以利用組件提供的方法/事件來實作這一點,而不是創建單獨的視窗級偵聽器。
該反應選部分將已經接近上點擊外,并提供onMenuClose你聽,并設定相應的狀態事件。我已經包含了一個useEffect用于在焦點狀態更改時將焦點分配給選擇,因為除非獲得焦點,否則它不會在外部注冊單擊,但是您可以根據需要在專案的背景關系中找到更優雅的解決方案。
這是一個簡單的沙箱示例
export default function App() {
const [isFocusingReactSelect, setIsFocusingReactSelect] = useState(false);
const selectRef = useRef();
useEffect(() => {
if (isFocusingReactSelect) {
selectRef.current.focus();
}
}, [isFocusingReactSelect]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>show select based on where you click</h2>
<div style={{ width: "100%", height: 200 }}>
{!isFocusingReactSelect ? (
<div
style={{
backgroundColor: "gray",
width: "100%",
height: 40,
cursor: "pointer"
}}
onClick={() => setIsFocusingReactSelect(true)}
>
<p>react-select</p>
</div>
) : (
<Select
ref={selectRef}
options={options}
closeMenuOnSelect={false}
onMenuClose={() => setIsFocusingReactSelect(false)}
/>
)}
</div>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362505.html
標籤:javascript 反应 反应选择
