Javascript 使用typescript将功能组件与道具的扩展运算符进行反应
如何使用排列操作来分解传递给组件的道具?我试过一些方法来做这件事,但没有运气Javascript 使用typescript将功能组件与道具的扩展运算符进行反应,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,如何使用排列操作来分解传递给组件的道具?我试过一些方法来做这件事,但没有运气 import React from 'react'; import "./button.component.css" function ButtonComponent( {onClick: ()=> void, caption:string, ...otherProps}) { return ( <button onClick={onClick} class
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;
从“React”导入React;
导入“/button.component.css”
函数按钮组件({onClick:()=>void,标题:string,…otherProps}){
返回(
{标题}
);
};
导出默认按钮组件;
这将导致以下错误:
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 | );
绑定元素“onClick”隐式具有“any”类型。TS7031
4 |
5 |
>6 |功能按钮组件({onClick,caption,…otherProps}){
| ^
7 |返回(
8 |{标题}
9 | );
您可以先声明一个接口,然后将其指定为类型
:
interface Props {
onClick: ()=> void;
caption:string,
otherProps: any
}
然后使用它:
ButtonComponent( {onClick, caption , otherProps}: Props)
也可以内联使用:
ButtonComponent( {onClick, caption , ...otherProps}: {onClick: ()=> void, caption:string, otherProps: any})
所以,我不能像我那样将var声明与它们的类型混合在一起?我必须始终指定Desconstruction变量,然后再指定它们的类型?我发誓我看到了更像我添加的代码的东西。我真的更喜欢它。它非常紧凑。当你接收道具时,你可以这样做,而不需要去结构化,但不是这样