Reactjs HTMLInputElement forwardRef不';我不接受这个名字

Reactjs HTMLInputElement forwardRef不';我不接受这个名字,reactjs,typescript,styled-components,Reactjs,Typescript,Styled Components,这是我的输入组件: import styled from 'styled-components' import React, { forwardRef } from 'react' type Props = { err: boolean maxWidth: string } export const Input = forwardRef<HTMLInputElement, Props>(({ ...rest }, ref) => { return <Sty

这是我的输入组件:

import styled from 'styled-components'
import React, { forwardRef } from 'react'

type Props = {
  err: boolean
  maxWidth: string
}

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

const StyledInput = styled.input<Props>``

你应该声明你的道具类型如下

static propTypes = {
      name: PropTypes.string,
      ...
 }

我希望这会有帮助

forwardRef中的第一个类型仅指定
ref
类型,因此不能将
HTMLInputElement
中的属性作为道具传递

相反,您应该通过添加
HTMLInputElement
类型作为选项来扩展
Props
类型

type Props = {
  err: boolean
  maxWidth: string
} & HTMLInputElement
但是,在这种情况下,您需要提供
HTMLInputElement
的所有200多个属性作为
输入的道具。这不好,但是
Typescript
有一个巧妙的小技巧。您可以改用
Partial

type Props = {
  err: boolean
  maxWidth: string
} & Partial<HTMLInputElement>
类型道具={
错误:布尔型
maxWidth:字符串
}&部分
现在,您需要提供自己定义的道具(
err
maxWidth
),并且可以选择从
HTMLInputElement
提供任何属性

希望这有帮助。

以下是解决方案:

interface Props extends React.ComponentPropsWithoutRef<'input'> {
  err?: boolean
  maxWidth?: string
}
接口道具扩展了React.ComponentPropsWithoutRef{
错误?:布尔值
maxWidth?:字符串
}

其他人是否出于某种原因省略了name属性?@JoeLloyd抱歉,我不明白这个问题。抱歉,我的建议根本不起作用,只是看到了你的道具界面。我想它可能在名字上使用了省略。你能提供完整的代码吗?只有“&部分”弹出另一个错误。错误是什么?我怀疑其中一个是
autoComplete
。您应该改为编写
autocomplete
。此外,您还必须提供
err
maxWidth
作为道具,因为它们是必需的。如果您希望它们也是可选的,请在
Props
类型定义中添加
err?
maxWidth?
。您可以使用codesandbox:看起来
样式化组件
包的内部类型与
HTMLInputElement
不匹配,因此无法使用该接口。我的回答修复了为您自己的组件添加可选道具的问题,但是您必须在这里阅读更多关于包问题的信息,并对此进行详细说明
type Props = {
  err: boolean
  maxWidth: string
} & HTMLInputElement
type Props = {
  err: boolean
  maxWidth: string
} & Partial<HTMLInputElement>
interface Props extends React.ComponentPropsWithoutRef<'input'> {
  err?: boolean
  maxWidth?: string
}