【发布时间】:2021-08-18 14:33:21
【问题描述】:
如何使用 rest 参数来接收 react 功能组件中的扩展属性?
这是我的组件:
import React from 'react';
import "./button.component.css"
interface IProps
{
onClick: ()=>void,
caption: string,
}
function ButtonComponent( {onClick, caption, ...otherProps} : IProps) {
return (
<button onClick={onClick} className="button" {...otherProps}>{caption}</button>
);
};
export default ButtonComponent;
我是这样使用它的:
<ButtonComponent id="register" caption="CREATE ACCOUNT" style={{width:"48%", backgroundColor:"#00AAFF", color:"#FFF"}} onClick={()=>{console.log("")} }></ButtonComponent>
这给出了错误:
TypeScript error in /Users/hexdump/Documents/Development/react/crwn-clothing/src/components/register-form/register-form.component.tsx(16,34): Type '{ id: string; caption: string; style: { width: string; backgroundColor: string; color: string; }; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & IProps'.
为什么不能在按钮标签属性中展开界面中不存在的属性?
【问题讨论】:
-
stackoverflow.com/questions/40032592/… 这就是你要找的东西:D
-
@AnhTuan 嗯,这对我来说似乎有点骇人听闻。我在打字稿存储库中看到人们多年来一直在要求解决这个问题......似乎他们还没有修复它:P。另一方面,这是针对 Typescript 2.1 的。情况有了很大改善。
-
同意,但我认为 type script 的主要目的是 'type' 。所以使用 ...otherProps,很难知道该道具中存储了什么样的数据:D
标签: javascript reactjs typescript