编译时反应接口函数抛出错误

时间:2020-04-24 13:08:41

标签: reactjs typescript react-hooks

我是新来的反应者,学习是我自己的反应。尝试编译我的项目时出现以下错误。任何帮助或建议,将不胜感激。

interface ConfirmProps{
  title : string;
  content : string;
  cancelCaption? : string;
  okCaption? :string;
  onOkClick: () => void;
}


const Confirm = (props: ConfirmProps) => {
  const {title, content, cancelCaption, okCaption, onOkClick}= props;

  const handleOkClick = () => {
    onOkClick();
  };

我遇到错误

Property 'onOkClick' is missing in type '{ title: string; content: string; cancelCaption: string; okCaption: string; }' but required in type 'ConfirmProps'.  TS2741

pic enter image description here

1 个答案:

答案 0 :(得分:0)

根据属性的定义,onClick是必需的道具。

要匹配该合同,您可以:

a)将道具设为可选。注意问号.?onOkClick && onOkClick();

interface ConfirmProps{
  title : string;
  content : string;
  cancelCaption? : string;
  okCaption? :string;
  onOkClick?: () => void;
}


const Confirm = (props: ConfirmProps) => {
  const {title, content, cancelCaption, okCaption, onOkClick}= props;

  const handleOkClick = () => {
    onOkClick && onOkClick();
  };

b)在父组件中使用Confirm时,您必须传递a函数

<Confirm
title= "title"
content= "content of confirm"
cancelCaption="No Way"
onClick={() => {/**Do something here**/}}
/>