createRef
tạo ra một đối tượng ref có thể chứa giá trị tùy ý.
class MyInput extends Component {
inputRef = createRef();
// ...
}
Tham khảo
createRef()
Gọi createRef
để khai báo một ref bên trong một component class.
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...
Tham số
createRef
không có tham số.
Giá trị trả về
createRef
trả về một đối tượng với một thuộc tính duy nhất:
current
: Ban đầu, nó được đặt thànhnull
. Bạn có thể đặt nó thành một giá trị khác sau này. Nếu bạn truyền đối tượng ref cho React dưới dạng một thuộc tínhref
cho một nút JSX, React sẽ đặt thuộc tínhcurrent
của nó.
Lưu ý
createRef
luôn trả về một đối tượng khác. Nó tương đương với việc tự viết{ current: null }
.- Trong một component function, bạn có thể muốn sử dụng
useRef
thay thế, nó luôn trả về cùng một đối tượng. const ref = useRef()
tương đương vớiconst [ref, _] = useState(() => createRef(null))
.
Cách sử dụng
Khai báo một ref trong một component class
Để khai báo một ref bên trong một component class, gọi createRef
và gán kết quả của nó cho một trường class:
import { Component, createRef } from 'react';
class Form extends Component {
inputRef = createRef();
// ...
}
Nếu bây giờ bạn truyền ref={this.inputRef}
cho một <input>
trong JSX của bạn, React sẽ điền this.inputRef.current
với nút DOM input. Ví dụ: đây là cách bạn tạo một nút tập trung vào 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> </> ); } }
Các lựa chọn thay thế
Chuyển đổi từ một class với createRef
sang một function với useRef
Chúng tôi khuyên bạn nên sử dụng component function thay vì component class trong code mới. Nếu bạn có một số component class hiện tại đang sử dụng createRef
, đây là cách bạn có thể chuyển đổi chúng. Đây là code gốc:
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> </> ); } }
Khi bạn chuyển đổi component này từ một class sang một function, hãy thay thế các lệnh gọi đến createRef
bằng các lệnh gọi đến 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> </> ); }