createRef
createRef 會建立一個 ref 物件,它可以包含任意值。
class MyInput extends Component {
inputRef = createRef();
// ...
}參考
createRef()
呼叫 createRef 可以在 類別元件 中宣告一個 ref。
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...參數
createRef 不接受任何參數。
回傳值
createRef 會回傳一個具有單一屬性的物件
current:初始值設定為null。您可以稍後將它設定為其他值。如果您將 ref 物件作為ref屬性傳遞給 JSX 節點的 React,React 會設定其current屬性。
注意事項
createRef總是回傳一個*不同*的物件。這相當於您自己撰寫{ current: null }。- 在函式元件中,您可能需要
useRef,它總是回傳相同的物件。 const ref = useRef()等同於const [ref, _] = useState(() => createRef(null))。
用法
在類別組件中宣告 ref...
要在 類別組件 中宣告 ref,請呼叫 createRef 並將其結果指派給類別欄位。
import { Component, createRef } from 'react';
class Form extends Component {
inputRef = createRef();
// ...
}如果您現在將 ref={this.inputRef} 傳遞給 JSX 中的 <input>,React 將使用 input DOM 節點填入 this.inputRef.current。例如,以下是建立一個讓 input 聚焦的按鈕的方法:
import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Focus the input </button> </> ); } }
替代方案...
從使用 createRef 的類別遷移到使用 useRef 的函式...
我們建議在新程式碼中使用函式組件而不是 類別組件。如果您有一些現有的類別組件使用 createRef,以下是您可以轉換它們的方法。這是原始程式碼:
import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Focus the input </button> </> ); } }
當您將此組件從類別轉換為函式時,請將對 createRef 的呼叫替換為對 useRef 的呼叫:
import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }