【问题标题】:React functional component with spread operator for props using typescript使用 typescript 为 props 的扩展运算符反应功能组件
【发布时间】:2021-05-12 15:22:27
【问题描述】:

如何使用展开操作来解构传递给组件的道具?我已经尝试了一些方法来做到这一点,但没有任何运气。

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 |     );

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    你可以先声明一个接口,然后赋值为type

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

    然后使用它:

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

    也可以内联使用:

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

    【讨论】:

    • 那么,我不能像以前那样将 var 声明与它们的类型混合在一起吗?我必须始终指定解构变量,然后指定它们的类型?我发誓我看到的东西更像我添加的代码。我真的很喜欢它。它非常紧凑。
    • 在不解构的情况下接收props时可以这样做,但不能这样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2021-09-02
    • 2023-04-04
    相关资源
    最近更新 更多