[英]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.