LoginSignup
2
1

More than 3 years have passed since last update.

React@16以降のref(createRef)でのtypescriptの書き方 備忘録

Posted at

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は使いたくないのが本音だけど、
現場によっては使っているので対応が必要

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1