Chakra UI使用AlertDialog时leastDestructiveRef和ref类型报错如何解决
问题原因
你声明cancelRef时未指定对应的元素类型,TypeScript默认推导的MutableRefObject类型和Chakra UI AlertDialog要求的leastDestructiveRef属性的元素引用类型不匹配。
解决方法
- 给
useRef指定正确的泛型类型,初始值设置为null:
import { useRef } from 'react'; // 绑定Button对应的原生DOM元素类型 const cancelRef = useRef<HTMLButtonElement>(null);
- 检查AlertDialog的嵌套结构是否符合要求,
leastDestructiveRef指向的Button必须放在AlertDialogContent内部,完整可运行的代码示例如下:
import { useDisclosure, AlertDialog, AlertDialogOverlay, AlertDialogContent, AlertDialogHeader, AlertDialogBody, AlertDialogFooter, Button } from '@chakra-ui/react'; import { useRef } from 'react'; function YourComponent() { const { isOpen, onOpen, onClose } = useDisclosure(); const cancelRef = useRef<HTMLButtonElement>(null); return ( <> <Button onClick={onOpen}>打开提示框</Button> <AlertDialog motionPreset="slideInBottom" leastDestructiveRef={cancelRef} onClose={onClose} isOpen={isOpen} isCentered > <AlertDialogOverlay> <AlertDialogContent> <AlertDialogHeader>操作确认</AlertDialogHeader> <AlertDialogBody>是否确认执行该操作?</AlertDialogBody> <AlertDialogFooter> <Button ref={cancelRef} onClick={onClose}>取消</Button> <Button colorScheme="red" ml={3} onClick={onClose}>确认</Button> </AlertDialogFooter> </AlertDialogContent> </AlertDialogOverlay> </AlertDialog> </> ) }
按照上述修改后类型报错会直接消失。
内容的提问来源于stack exchange,提问作者Raphael Jayme
相关产品推荐
相关产品推荐

