Reactv16以降のref
typescriptでrefを使う際に悩んだので備忘録として残す
昔の書き方
以前のrefはこんな感じに書いていた(多分)
export class SampleComponent extends React.Component<Props, State> {
private inputElement: HTMLInputElement
constructor(props: Props) {
super(props);
this.inputElement = ""
}
render(){
return(
<input ref={input => this.inputElement = input} />
)
}
}
最近の書き方
Reactv16以降での新しい createRef
をしようした場合
RefObjectに型を入れることでチェックできる
import * as React from 'react';
export class SampleComponent extends React.Component<Props, State> {
private inputElement: React.RefObject<HTMLInputElement>
constructor(props: Props) {
super(props);
this.inputElement = React.createRef();
}
render(){
return(
<input ref={this.inputElement} />
)
}
}
まぁ、あんまりrefは使いたくないのが本音だけど、
現場によっては使っているので対応が必要