LoginSignup
ryu110
@ryu110

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

React,TypeScriptについて。型定義がわからない

const cancelRef = React.useRef<>();
leastDestructiveRef={cancelRef}
Button ref={cancelRef} onClick={onClose}>

上記の3つについて、型定義をしなくてはなりませんがわからないです。。。。
下記のchakra-uiとまったく同じです。ここには下記のように書かれています。
【AlertDialog requires that you provide the leastDestructiveRef prop.】
https://chakra-ui.com/docs/overlay/alert-dialog

下記がエラー内容

型 'MutableRefObject<HTMLElement | undefined>' を型 'RefObject<FocusableElement>' に割り当てることはできません。
プロパティ 'current' の型に互換性がありません。
型 'HTMLElement | undefined' を型 'FocusableElement | null' に割り当てることはできません。
型 'undefined' を型 'FocusableElement | null' に割り当てることはできません。ts(2322)
alert-dialog.d.ts(4, 5): 予期された型は、型 'IntrinsicAttributes & AlertDialogProps' に対してここで宣言されたプロパティ 'leastDestructiveRef' から取得されています

下記がコードです。

import {
  AlertDialog,
  AlertDialogBody,
  AlertDialogContent,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogOverlay,
  Button,
} from "@chakra-ui/react";
import React from "react";
import { FC, memo, ReactNode } from "react";

type Props = {
  cancelRef: any
}

const AlertDialogModal: FC<Props> = () => {
  const [isOpen, setIsOpen] = React.useState(false);
  const onClose = () => setIsOpen(false);
  const cancelRef = React.useRef<HTMLElement>();

  return (
    <>
      <Button colorScheme="red" onClick={() => setIsOpen(true)}>
        Delete Customer
      </Button>

      <AlertDialog
        isOpen={isOpen}
        leastDestructiveRef={cancelRef}
        onClose={onClose}
      >
        <AlertDialogOverlay>
          <AlertDialogContent>
            <AlertDialogHeader fontSize="lg" fontWeight="bold">
              Delete Customer
            </AlertDialogHeader>

            <AlertDialogBody>
              Are you sure? You can't undo this action afterwards.
            </AlertDialogBody>

            <AlertDialogFooter>
              <Button ref={cancelRef} onClick={onClose}>
                Cancel
              </Button>
              <Button colorScheme="red" onClick={onClose} ml={3}>
                Delete
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialog>
    </>
  );
};
1

1Answer

いまcancelRefはbuttonのref属性に渡そうとしているので、button要素の型であるHTMLButtonElementを指定する必要があります。(HTMLElement → HTMLButtonElement はダウンキャストなので暗黙には行われません。)

また、useRefはオーバーロードが3つあります。useRef<T>() だと結果の型が React.MutableRefObject<T> であるオーバーロードが選ばれてしまい、ref={cancelRef} の部分で型エラーになってしまいます。引数にnullを指定すると結果が React.RefObject<T> になるオーバーロードに解決されます。

    const cancelRef = React.useRef<HTMLButtonElement>(null);
8

Comments

  1. @ryu110

    Questioner
    参考になりました。ありがとうございます。

Your answer might help someone💌