【问题标题】:React interface function throwing error when compiling编译时反应接口函数抛出错误
【发布时间】:2020-04-24 13:08:41
【问题描述】:

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

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

图片

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    根据属性的定义,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**/}}
    />
    

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多