【发布时间】:2021-08-08 21:23:28
【问题描述】:
您好,我刚刚开始使用 typescript 并做出反应!
我有这个简单的按钮组件
import React from 'react'
interface Props{
className?:string,
onClick:()=> void,
children: React.ReactNode
}
export const Button:React.FC<Props> = ({onClick = ()=>1,children,className = "",...rest}) =>{
return(
<button onClick={onClick} className={"r-button cursor-p br " + className} {...rest}>
{children}
</button>)
}
它工作得很好,但是如果我尝试向组件添加一个我只用于样式的属性,就像这样
<Button loading="true" onClick={()=>console.log("yoohoi")}>Click me!</Button>
我在加载属性中收到此错误
Type '{ children: (Element | ReactNode)[]; className: string; onClick: () => Promise<void>; loading: string; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
Property 'loading' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
所以我的问题是如何处理仅用于样式目的的传递属性而不必在道具界面中声明它们?我认为 ...rest 会完成这项工作:/
【问题讨论】:
-
您可以为此使用 data-* 属性。但是,为什么不只使用自定义类,例如
classNanme='loading'? -
:O好像很喜欢,为什么数据加载有效?
-
因为数据属性正是为此目的而设计的,幸运的是 React 尊重这一点),请参阅答案
标签: reactjs typescript