簡體   English   中英

使用 typescript 為 props 的擴展運算符反應功能組件

[英]React functional component with spread operator for props using typescript

如何使用擴展操作來解構傳遞給組件的道具? 我嘗試了一些方法來做到這一點,但沒有任何運氣。

import React from 'react';
import "./button.component.css"



function ButtonComponent( {onClick: ()=> void, caption:string, ...otherProps}) {
    return (
        <button onClick={onClick} className="button" {...otherProps}>{caption}</button>
    );
};

export default ButtonComponent;

這給出了以下錯誤:

Binding element 'onClick' implicitly has an 'any' type.  TS7031

    4 | 
    5 | 
  > 6 | function ButtonComponent({onClick, caption, ...otherProps}) {
      |                           ^
    7 |     return (
    8 |         <button onClick={onClick} className="button" {...otherProps}>{caption}</button>
    9 |     );

您可以先聲明一個接口,然后將其分配為type

interface Props {
  onClick: ()=> void;
  caption:string,
  otherProps: any
}

然后使用它:

ButtonComponent( {onClick, caption , otherProps}: Props)

或者它可以內聯使用:

ButtonComponent( {onClick, caption , ...otherProps}: {onClick: ()=> void, caption:string, otherProps: any})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM