Как правильно проверить input.focus() на строгое равенство null и undefined (React, TS)?
При строгой проверке на null и undefined выходит ошибка. Я правильно понимаю, что нужно указать тип? В каком месте его указывать, что-бы исправить ошибку? Ошибка выходит когда я возвращаю return в обоих условиях
const textInput = useRef<HTMLInputElement|null>(null)
if (props.active) {
if (typeof textInput === "undefined") {
return
}
if (textInput === null) {
return
}
textInput.current?.focus()
}
return(
<input type="text" ref={textInput} />
)
Ответы (1 шт):
Автор решения: p1uton
→ Ссылка
Чтобы просто проверить, что textInput.current существует можно сделать так:
if (textInput.current) {
textInput.current.focus();
}
Не нужно проверять отдельно на null и undefined.
import { useEffect, useRef } from "react";
type AppProps = {
active: boolean;
};
export const App: React.FC<AppProps> = (props) => {
const textInput = useRef<HTMLInputElement>(null);
useEffect(() => {
if (props.active) {
if (textInput.current) {
textInput.current.focus();
}
}
}, []);
return <input type="text" ref={textInput} />;
};