【问题标题】:Property 'label' is missing in type '{ handleClick: () => void; }' but required in type '{ handleClick: () => void; label: string; }'类型“{ handleClick: () => void; 中缺少属性“标签”; }' 但在类型 '{ handleClick: () => void; 中是必需的标签:字符串; }'
【发布时间】:2020-03-19 11:08:28
【问题描述】:

我在描述我的道具类型时遇到了问题。我在以下代码行中遇到错误:

 <PostButton handleClick={props.upvote}/>
  <PostButton2 handleClick={props.downvote}/>

错误是:

类型'{ handleClick: () => void; 中缺少属性'label' }' 但 '{ handleClick: () => void; 类型中需要标签:字符串; }'.ts(2741) Comments.tsx(62, 55): 'label' 在这里声明。

当我尝试删除 'label: string; ' 从我的函数道具中,它会抛出一个错误说明:

类型'{ handleClick: () => void; 上不存在属性'label' }'。

这是我的代码:

function Button(props: { handleClick: () => void;  }) {

    let style = {
        paddingRight: 100,

    };
    return (
        <div>
            <button style={style} onClick={() => props.handleClick()}>
                {props.label}

                    PostButton
            </button>
        </div>
    );
}

【问题讨论】:

    标签: reactjs typescript types jsx next.js


    【解决方案1】:

    在函数 PostButton 中,您尝试打印道具中不存在的 {props.label},尝试删除 props: { handleClick: () =&gt; void; } 并仅使用 function PostButton()。我看到太多的处理程序被分配什么都不做,为什么不把它们也删除并清理代码。

    更好的解决方案: 如果您想继续使用{props.label},那么只需在调用函数时添加它:&lt;PostButton handleClick={props.upvote} label="this is a label, it can be left blank"/&gt;

    【讨论】:

      【解决方案2】:

      您的PostButton 都在return 中使用{props.label},因此您必须将标签作为道具传递

      function PostButton(props: { handleClick: () => void; title: string  }) {....}
      
      <PostButton handleClick={props.upvote} title="titlePostButton"/>
      
      <PostButton2 handleClick={props.downvote} title="titlePostButton2"/>
      

      【讨论】:

        猜你喜欢
        • 2019-06-25
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 2020-05-18
        • 2019-09-19
        • 2020-12-25
        • 2020-08-24
        • 1970-01-01
        相关资源
        最近更新 更多