要素参照関数
Reactでは、要素参照を使用して要素やコンポーネントのインスタンスを取得できます。
関数コンポーネントの要素参照
関数コンポーネント内で、要素参照はuseRefフックでアクセスされます。
1import {useRef} from 'react';2import * as React from 'react';3
4function MyComponent() {5 const buttonRef = useRef<null | HTMLButtonElement>(null); 6 buttonRef as {current: null | HTMLButtonElement}; // useRef wraps the ref value in an object7 return <button ref={buttonRef}>Toggle</button>;8}5:21-5:58: Cannot call hook [1] because React hooks can only be called within components or hooks. [react-rule-hook]
useRefは要素参照の値をcurrentプロパティを持つオブジェクトにラップすることに注意してください。これは、要素参照の値を受け入れるものすべての型に反映される必要があります。
クラスコンポーネントの要素参照
クラスコンポーネントの要素参照は、関数コンポーネントに似ています。クラスコンポーネントを作成するには、クラスにプロパティを追加し、React.createRefの結果をそのプロパティに割り当てます。
1import * as React from 'react';2
3class MyComponent extends React.Component<{}> {4 // The `null` here is important because you may not always have the instance.5 buttonRef: {current: null | HTMLButtonElement};6
7 constructor() {8 super();9 this.buttonRef = React.createRef<HTMLButtonElement>();10 }11
12 render(): React.Node {13 return <button ref={this.buttonRef}>Toggle</button>;14 }15}useRefとcreateRefの注目すべき違いの1つは、createRefはデフォルト値を受け付けないという点です。要素参照をnullの値で初期化します。これは、DOM要素はMyComponentの最初のレンダリングまで存在しないため、nullの値を使用する必要があるためです。
繰り返しますが、要素参照の値はcurrentプロパティを持つオブジェクトにラップされていることに注意してください。