简体   繁体   English

如何处理 TS React 项目中的意外道具?

[英]How to deal with unexpected props in TS React project?

For example, I have a custom button component.例如,我有一个自定义按钮组件。

<button type={type} className={classes} {...props}>
  {!!children && <span>{children}</span>}
</button>

I passed other props that I don't want to predict with destructing.我通过了其他我不想用破坏来预测的道具。 But TS will throw an error when I will try to pass, for example, disabled prop coz it not defined in the TS interface.但是当我尝试传递时,TS 会抛出一个错误,例如, disabled prop 因为它没有在 TS 接口中定义。

Is there some way to deal with this?有什么办法可以解决这个问题吗? Or the only way is to define all possible pros in an interface?或者唯一的方法是在界面中定义所有可能的优点?

For your specific case, your custom button props could extend HTML button props对于您的具体情况,您的自定义按钮道具可以扩展 HTML 按钮道具

interface MyButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  children: React.ReactNode;
}

function MyButton({ children, ...props }: MyButtonProps) {
  return <button {...props}>{children}</props>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM