我在 Shadcn 的抽屉组件中有一些表单,在输入上打字会显示键盘,并且可能会发生两种奇怪的情况,输入隐藏在键盘后面,或者抽屉内出现空白空间,将输入方式推到上部,也隐藏它们。
我尝试控制显示键盘时的高度,但情况变得更糟。
useEffect(() => {
function onVisualViewportChange() {
const visualViewportHeight = window.visualViewport.height;
const keyboardHeight = window.innerHeight - visualViewportHeight;
// Difference between window height and height excluding the keyboard
const diffFromInitial = window.innerHeight - keyboardHeight;
const drawerHeight = drawerRef.current.getBoundingClientRect().height || 0;
drawerRef.current.style.height = `${visualViewportHeight - drawerHeight}px`;
drawerRef.current.style.bottom = `${Math.max(diffFromInitial, 0)}px`;
}
window.visualViewport?.addEventListener("resize", onVisualViewportChange);
return () =>
window.visualViewport?.removeEventListener("resize", onVisualViewportChange);
}, [])
<DrawerContent ref={drawerRef}>
我就这样解决了这个问题
const Component = () => {
const formContainerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const handleResize = () => {
if (formContainerRef.current) {
formContainerRef.current.style.setProperty('bottom', `env(safe-area-inset-bottom)`);
}
};
if (window.visualViewport) {
window.visualViewport.addEventListener("resize", handleResize);
handleResize(); // Initial call in case the keyboard is already open
}
return () => {
if (window.visualViewport) {
window.visualViewport.removeEventListener("resize", handleResize);
}
};
}, []);
return (
....
<DrawerContent ref={formContainerRef} className="min-h-[70vh]">
<Form .... />
</DrawerContent>
.....
);
};