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
}