Введите '{ фокус(): недействительным; }" отсутствуют следующие свойства типа "HTMLdivElement": align, addEventListener, removeEventListener, accessKey и 234 more.ts(2740) index.d.ts(1041, 79): ожидаемый тип исходит из возвращаемого типа этой подписи.
вот код компонента:
import React, { forwardRef, useImperativeHandle, useRef } from "react";
type Ref = HTMLDivElement | null;
type SwiperProps = {
children?: React.ReactNode | null;
selectedIndex?: number;
};
const Swiper = forwardRef<Ref, SwiperProps>(
({ children = null }: SwiperProps, ref) => {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current.focus();
}
}));
return (
<div ref = {ref}>
{children}
<input type = "text" ref = {inputRef} />
</div>
);
}
);
export default Swiper;
полный код находится в codeandbox;
https://codesandbox.io/s/useimperativehandlecomponenterror-lowon
Вы перепутали определения типов ваших рефов:
import React, { forwardRef, useImperativeHandle, useRef } from "react";
type Ref = {
focus: () => void
} | null;
type SwiperProps = {
children?: React.ReactNode | null;
selectedIndex?: number;
};
const Swiper = forwardRef<Ref, SwiperProps>(
({ children = null }: SwiperProps, ref) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current?.focus();
}
}));
return (
<div>
{children}
<input type = "text" ref = {inputRef} />
</div>
);
}
);
export default Swiper;
Тип, который вы предоставляете, должен описывать ваш императивный дескриптор.
Моя репутация слишком низкая, я не могу голосовать за ваш ответ
не нужно голосовать, просто примите это
@thedude Это больше не работает. На app.tsx:10
у нас ошибка при вызове focus
.
Я обновил ссылку, чтобы исправить ошибку типа
Если вы нашли этот ответ полезным, отметьте его как принятый ответ