You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chakra UI使用AlertDialog时leastDestructiveRef和ref类型报错如何解决

问题原因

你声明cancelRef时未指定对应的元素类型,TypeScript默认推导的MutableRefObject类型和Chakra UI AlertDialog要求的leastDestructiveRef属性的元素引用类型不匹配。

解决方法

  1. 给useRef指定正确的泛型类型,初始值设置为null:
import { useRef } from 'react';

// 绑定Button对应的原生DOM元素类型
const cancelRef = useRef<HTMLButtonElement>(null);
  1. 检查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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:09:00