React TS 获取共享组件的道具 [英] React TS get prop for shared component

查看:49
本文介绍了React TS 获取共享组件的道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让打字稿知道错误类型?

How to let typescript know about err type?

type InputProps = {
  err?: boolean
}

export const Input = forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<'input'>>(({ err, ...rest }, ref) => {
  // some use for err here
  return <StyledInput {...rest} ref={ref} />
})


const StyledInput = styled.input<InputProps>`
  box-shadow: inset 0 0 0 1px ${({ err, theme }) => (err ? theme.badColor : theme.primaryColor)};
`

错误是:

类型上不存在属性 'err''PropsWithChildren,HTMLInputElement>, "表单" |"风格" |标题" |模式" |钥匙" |接受" |"替代" |自动完成" |... 276 更多... |onTransitionEndCapture">>'.ts(2339)

Property 'err' does not exist on type 'PropsWithChildren, HTMLInputElement>, "form" | "style" | "title" | "pattern" | "key" | "accept" | "alt" | "autoComplete" | ... 276 more ... | "onTransitionEndCapture">>'.ts(2339)

推荐答案

使用 InputProps 类型作为第二个通用参数:

Use the InputProps-type as your second generic argument:

export const Input = forwardRef<HTMLInputElement, InputProps>(({ err, ...rest }, ref) => {
  return <StyledInput {...rest} ref={ref} />
});

这篇关于React TS 获取共享组件的道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆