React Refs with TypeScript

Jayson Chiang
Feb 27, 2021

--

實作一個帶有 Textbox 的 React Component,在 componentDidMount 的時侯希望能 focus 指定的 <input />

改寫成 TypeScript 的時侯, useEffect 裡的 inputRef.current.focus() 會噴錯,因為 initial 的 refs 是 null ,他有可能一直是 null ,TypeScript也沒辦法確定 inputRefcurrent 這個property。

所以需要在 useRef 加上這個 Element 對應的型別 HTMLInputElement,而且還要考量有 null ,所以寫起來是 useRef<HTMLInputElement | null>(null)

然後在 useEffect 裡要加上 Type Guard ,讓不同的型別有各自的行為。

--

--

No responses yet