【发布时间】:2021-05-19 19:06:54
【问题描述】:
我正在努力在带有打字稿的input 上使用 useRef。我检查了许多链接,例如 this one,但我仍然遇到同样的错误。
const MainHeader: React.FC = () => {
const InputStyled = styled(Input)`
// some basic css
`;
const searchElement = useRef<HTMLInputElement>(null);
return (
<>
<InputStyled full ref={searchElement} type="search" />
</>
);
}
我的Input 组件:
export type SearchFieldProps = React.InputHTMLAttributes<HTMLInputElement> & {
full?: boolean;
medium?: boolean;
light?: boolean;
};
const SearchField = styled.input<SearchFieldProps>`
// css rules here
`;
const Input: React.FC<SearchFieldProps> = (props) => <SearchField {...props} />;
export default Input;
我认为我在这里没有做任何异国情调的事情,但它会返回:
No overload matches this call.
Overload 1 of 2, '(props: Pick<Pick<PropsWithChildren<SearchFieldProps>, "form" | "slot" | "style" | "title" | "pattern" | "type" | "name" | "defaultChecked" | ... 279 more ... | "light"> & Partial<...>, "form" | ... 286 more ... | "light"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
Type '{ ref: RefObject<HTMLInputElement>; full: true; placeholder: string | undefined; type: string; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<PropsWithChildren<SearchFieldProps>, "form" | "slot" | "style" | "title" | "pattern" | ... 282 more ... | "light"> & Partial<...>, "form" | ... 286 more ... | "light"> & { ...; } & { ...; }'.
Property 'ref' does not exist on type 'IntrinsicAttributes & Pick<Pick<PropsWithChildren<SearchFieldProps>, "form" | "slot" | "style" | "title" | "pattern" | ... 282 more ... | "light"> & Partial<...>, "form" | ... 286 more ... | "light"> & { ...; } & { ...; }'.
Overload 2 of 2, '(props: StyledComponentPropsWithAs<FC<SearchFieldProps>, any, {}, never, FC<SearchFieldProps>>): ReactElement<...>', gave the following error.
Type '{ ref: RefObject<HTMLInputElement>; full: true; placeholder: string | undefined; type: string; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<PropsWithChildren<SearchFieldProps>, "form" | "slot" | "style" | "title" | "pattern" | ... 282 more ... | "light"> & Partial<...>, "form" | ... 286 more ... | "light"> & { ...; } & { ...; }'.
Property 'ref' does not exist on type 'IntrinsicAttributes & Pick<Pick<PropsWithChildren<SearchFieldProps>, "form" | "slot" | "style" | "title" | "pattern" | ... 282 more ... | "light"> & Partial<...>, "form" | ... 286 more ... | "light"> & { ...; } & { ...; }'.
欢迎任何想法/建议!
谢谢
【问题讨论】:
-
看起来它希望您的
InputStyled组件声明ref属性。我没有使用样式组件,但也许您创建了一个包装器,在 ref 属性中添加并返回样式组件?
标签: reactjs typescript use-ref