输入 '{ closeCallback: MouseEventHandler<HTMLElement>; }' 不可分配给类型 'IntrinsicAttributes & MouseEvent

问题描述 投票:0回答:1

在下面的组件中,我显示了一个对话框,该对话框将 closeCallback 函数作为道具。基本模型的代码基本上接受此道具并在单击十字按钮时调用它。但随后我并没有真正消失,而是注意到控制台日志中存在错误,即 closeCallback 不是一个函数。

还注意到

closeCallback
中的
CloseModalButton
没有用红色划线。当我将鼠标悬停在它上面时,我看到以下错误,

Type '{ closeCallback: MouseEventHandler<HTMLElement>; }' is not assignable to type 'IntrinsicAttributes & MouseEventHandler<HTMLElement>'.
  Property 'closeCallback' does not exist on type 'IntrinsicAttributes & MouseEventHandler<HTMLElement>'.ts(2322)

不确定为什么上面的 closeCallback 被包含在一个对象中,这是否与它有关?我该如何解决这个问题?

以下代码,

export default function NotesPage() {
  const [showAddNoteDialog, setShowAddNoteDialog] = useState(false);
  const handleBtnClick = () => setShowAddNoteDialog(true);
  return (
    <>
      ....
      <section className="container mx-auto p-2">
      <section>
        {showAddNoteDialog && (
          <BasicModal closeCallback={() => setShowAddNoteDialog(false)}>{/* Change the type of closeCallback */}
            <Note />
          </BasicModal>
        )}
        ....
      </section>
    </>
  );
}

基本模态,

type ModalProps = {
  closeCallback: React.MouseEventHandler<HTMLElement>;
} & PropsWithChildren;

export const BasicModal = (props: ModalProps) => {
  console.log('closeCallback', props.closeCallback);
  const { closeCallback } = props;
  return (
    <section className="basic-modal">
      <CloseModalButton closeCallback={closeCallback} />
      {props.children}
    </section>
  );
};

关闭模态按钮,

export const CloseModalButton = (closeCallback: React.MouseEventHandler<HTMLElement>) => {
  return (
    <button
      type="button"
      onClick={() => closeCallback()}> X </button>);
   }
reactjs typescript remix.run
1个回答
0
投票

React
Components
props
作为对象而不是函数参数。

CloseModalButton
中,以下更改应该修复打字稿错误

export const CloseModalButton = (
  props: { closeCallback: React.MouseEventHandler<HTMLElement> }
) => {
  const closeCallback = props.closeCallback
  return (
    <button
      type="button"
      onClick={closeCallback}
    > X </button>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.