You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/docs/refs-and-the-dom.md
+54-55Lines changed: 54 additions & 55 deletions
Original file line number
Diff line number
Diff line change
@@ -10,34 +10,33 @@ redirect_from:
10
10
- "tips/expose-component-functions.html"
11
11
- "tips/children-undefined.html"
12
12
---
13
+
Refs là một cách giúp chúng ta truy cập đến những nút DOM hoặc những phần tử React được tạo ra trong phương thức render.
13
14
14
-
Refs provide a way to access DOM nodes or React elements created in the render method.
15
+
Trong luồng dữ liệu của React, [props](/docs/components-and-props.html) là cách duy nhất để các component cha tương tác với component con. Để cập nhật component con, ta phải re-render nó với các props mới. Tuy nhiên, một số trường hợp buộc ta phải thay đổi thành phần con bên ngoài luồng dữ liệu điển hình của React. Component con được sửa đổi có thể là một instance của một React component, hoặc nó có thể là một DOM element. Với những trường hợp trên, ta có thể xử lý bằng Refs.
15
16
16
-
In the typical React dataflow, [props](/docs/components-and-props.html) are the only way that parent components interact with their children. To modify a child, you re-render it with new props. However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component, or it could be a DOM element. For both of these cases, React provides an escape hatch.
17
+
### Khi nào sử dụng Refs {#when-to-use-refs}
17
18
18
-
### When to Use Refs {#when-to-use-refs}
19
+
Một vài trường hợp hữu ích để sử dụng refs:
19
20
20
-
There are a few good use cases for refs:
21
+
* Quản lý focus, text selection, hoặc media playback.
22
+
* Trigger animation của một element khác.
23
+
* Tích hợp những thư viện DOM từ bên thứ ba.
21
24
22
-
* Managing focus, text selection, or media playback.
23
-
* Triggering imperative animations.
24
-
* Integrating with third-party DOM libraries.
25
+
Tránh sử dụng refs trong trường hợp chúng ta có thể khai báo.
25
26
26
-
Avoid using refs for anything that can be done declaratively.
27
+
Ví dụ, thay vì hiển thị phương thức `open()` và `close()` trong `Dialog` component, thì chúng ta sẽ sử dụng `isOpen` như một prop để xử lý nó.
27
28
28
-
For example, instead of exposing `open()` and `close()` methods on a `Dialog` component, pass an `isOpen` prop to it.
29
+
### Không nên lạm dụng Refs {#dont-overuse-refs}
29
30
30
-
### Don't Overuse Refs {#dont-overuse-refs}
31
+
Chúng ta hay có xu hướng sử dụng Refs để xử lý mọi thử xảy ra trong ứng dụng của mình. Nếu rơi vào trường hợp này, thì lời khuyên là bạn nên dành thời gian để suy nghĩ nhiều hơn về vị trí mà bạn nên đặt State trong hệ thống cập bậc component (Component Hierarchy) của bạn. Thông thường, để rõ ràng nhất, thì vị trí State sẽ được đặt ở cấp bậc cao nhất của Component Hierarchy. Bạn có thể tham khảo thêm hướng dẫn và các ví dụ tại đây [Lifting State Up](/docs/lifting-state-up.html).
31
32
32
-
Your first inclination may be to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. See the [Lifting State Up](/docs/lifting-state-up.html) guide for examples of this.
33
-
34
-
> Note
33
+
> Lưu ý
35
34
>
36
-
> The examples below have been updated to use the `React.createRef()` API introduced in React 16.3. If you are using an earlier release of React, we recommend using [callback refs](#callback-refs)instead.
35
+
> Những ví dụ bên dưới đã được cập nhật để sử dụng `React.createRef()` API được giới thiệu trong React 16.3. Nếu bạn sử dụng những phiên bản trước, React khuyên bạn nên sử dụng [callback refs](#callback-refs)để thay thế.
37
36
38
37
### Creating Refs {#creating-refs}
39
38
40
-
Refs are created using `React.createRef()`and attached to React elements via the `ref` attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
39
+
Refs được khởi tạo bằng `React.createRef()`và được gắn vào các React element thông qua thuộc tính `ref`. Refs thường được gán cho một element nào đó, tại đó chúng ta có thể tham chiếu đến tất cả các thành phần bên trong nó.
41
40
42
41
```javascript{4,7}
43
42
class MyComponent extends React.Component {
@@ -51,44 +50,44 @@ class MyComponent extends React.Component {
51
50
}
52
51
```
53
52
54
-
### Accessing Refs {#accessing-refs}
53
+
### Truy cập Refs {#accessing-refs}
55
54
56
-
When a ref is passed to an element in `render`, a reference to the node becomes accessible at the `current`attribute of the ref.
55
+
Khi một element có chứa ref `render`, chúng ta có thể sử dụng một thuộc tính của ref là `current`để truy cập đến node hiện tại.
57
56
58
57
```javascript
59
58
constnode=this.myRef.current;
60
59
```
61
60
62
-
The value of the ref differs depending on the type of the node:
61
+
Giá trị tham chiếu khác nhau, phụ thuộc vào loại cuả node:
63
62
64
-
-When the `ref`attribute is used on an HTML element, the `ref`created in the constructor with `React.createRef()` receives the underlying DOM element as its `current`property.
65
-
-When the `ref`attribute is used on a custom class component, the `ref`object receives the mounted instance of the component as its `current`.
66
-
-**You may not use the `ref`attribute on function components**because they don't have instances.
63
+
-Khi thuộc tính `ref`được sử dụng trong HTML element, `ref`sẽ nhận DOM element bên dưới làm thuộc tính `current`của nó.
64
+
-Khi thuộc tính `ref`được sử dụng trong class component tùy chỉnh, `ref`sẽ nhận instance của component làm thuộc tính `current` của nó.
65
+
-**Bạn không thể sử dụng thuộc tính `ref`trong function components**vì nó không có instances.
67
66
68
-
The examples below demonstrate the differences.
67
+
Các ví dụ dưới đây chứng minh sự khác biệt:
69
68
70
-
#### Adding a Ref to a DOM Element {#adding-a-ref-to-a-dom-element}
69
+
#### Thêm Ref vào một DOM Element {#adding-a-ref-to-a-dom-element}
71
70
72
-
This code uses a`ref`to store a reference to a DOM node:
71
+
Đoạn code sử dụng`ref`để lưu trữ một tham chiếu đến một DOM node:
73
72
74
73
```javascript{5,12,22}
75
74
class CustomTextInput extends React.Component {
76
75
constructor(props) {
77
76
super(props);
78
-
// create a ref to store the textInput DOM element
// Explicitly focus the text input using the raw DOM API
85
-
// Note: we're accessing "current" to get the DOM node
84
+
// Note: Chúng ra truy cập đến "current" để lấy DOM node
86
85
this.textInput.current.focus();
87
86
}
88
87
89
88
render() {
90
-
// tell React that we want to associate the <input> ref
91
-
// with the `textInput` that we created in the constructor
89
+
// Nói với React chúng ta muốn liên kết tới <input> ref
90
+
// Với `textInput` chúng ta đã tạo ở constructor
92
91
return (
93
92
<div>
94
93
<input
@@ -105,11 +104,11 @@ class CustomTextInput extends React.Component {
105
104
}
106
105
```
107
106
108
-
React will assign the `current`property with the DOM element when the component mounts, and assign it back to`null`when it unmounts. `ref`updates happen before `componentDidMount`or`componentDidUpdate` lifecycle methods.
107
+
React sẽ gắn `current`cho DOM element khi component mounts, và gắn nó trở lại`null`khi unmounts. `ref`được cập nhật trước `componentDidMount`hoặc`componentDidUpdate`.
109
108
110
-
#### Adding a Ref to a Class Component {#adding-a-ref-to-a-class-component}
109
+
#### Thêm Ref vào Class Component {#adding-a-ref-to-a-class-component}
111
110
112
-
If we wanted to wrap the `CustomTextInput`above to simulate it being clicked immediately after mounting, we could use a ref to get access to the custom input and call its `focusTextInput`method manually:
111
+
Nếu chúng ta muốn wrap `CustomTextInput`bên trên để nó được click ngay sau khi mounting, chúng ta có thể sử dụng một ref để có quyền truy cập vào input, tùy chỉnh và gọi phương thức `focusTextInput`của nó theo cách thủ công:
113
112
114
113
```javascript{4,8,13}
115
114
class AutoFocusTextInput extends React.Component {
@@ -130,17 +129,17 @@ class AutoFocusTextInput extends React.Component {
130
129
}
131
130
```
132
131
133
-
Note that this only works if `CustomTextInput`is declared as a class:
132
+
Chú ý nó chỉ hoạt động nếu `CustomTextInput`được khai báo dưới dạng class:
134
133
135
134
```js{1}
136
135
class CustomTextInput extends React.Component {
137
136
// ...
138
137
}
139
138
```
140
139
141
-
#### Refs and Function Components {#refs-and-function-components}
140
+
#### Refs và Function Components {#refs-and-function-components}
142
141
143
-
By default, **you may not use the `ref`attribute on function components**because they don't have instances:
142
+
Mặc định, **bạn không thể sử dụng thuộc tính `ref`trong function components**vì nó không có instances:
144
143
145
144
```javascript{1,8,13}
146
145
function MyFunctionComponent() {
@@ -153,21 +152,21 @@ class Parent extends React.Component {
153
152
this.textInput = React.createRef();
154
153
}
155
154
render() {
156
-
// This will *not* work!
155
+
// Nó sẽ không thực hiện được
157
156
return (
158
157
<MyFunctionComponent ref={this.textInput} />
159
158
);
160
159
}
161
160
}
162
161
```
163
162
164
-
If you want to allow people to take a`ref`to your function component, you can use [`forwardRef`](/docs/forwarding-refs.html) (possibly in conjunction with [`useImperativeHandle`](/docs/hooks-reference.html#useimperativehandle)), or you can convert the component to a class.
163
+
Nếu bạn muốn cho phép mọi người sử dụng`ref`từ function component của bạn, bạn có thể dùng [`forwardRef`](/docs/forwarding-refs.html) (có thể kết hợp với [`useImperativeHandle`](/docs/hooks-reference.html#useimperativehandle)), hoặc bạn có thể chuyển đổi component thành class.
165
164
166
-
You can, however, **use the `ref`attribute inside a function component**as long as you refer to a DOM element or a class component:
165
+
Tuy nhiên, bạn có thể **sử dụng thuộc tính `ref`bên trong function component**miễn là bạn tham chiếu đến phần tử DOM hoặc class component:
167
166
168
167
```javascript{2,3,6,13}
169
168
function CustomTextInput(props) {
170
-
// textInput must be declared here so the ref can refer to it
169
+
// textInput phải được khai báo ở đây để ref có thể tham chiếu đến nó
171
170
const textInput = useRef(null);
172
171
173
172
function handleClick() {
@@ -189,25 +188,25 @@ function CustomTextInput(props) {
189
188
}
190
189
```
191
190
192
-
### Exposing DOM Refs to Parent Components {#exposing-dom-refs-to-parent-components}
191
+
### Hiển thị DOM Refs cho Components cha {#exposing-dom-refs-to-parent-components}
193
192
194
-
In rare cases, you might want to have access to a child's DOM node from a parent component. This is generally not recommended because it breaks component encapsulation, but it can occasionally be useful for triggering focus or measuring the size or position of a child DOM node.
193
+
Một số ít trường hợp, bạn muốn có quyền truy cập vào DOM node của element con từ component cha. Nhưng chúng tôi không khuyến khích điều đó vì nó sẽ phá hủy tính đóng gói của component, một số ít nó hữu dụng khi trigger focus hoặc xác định kích thước, vị trí của một DOM node con.
195
194
196
-
While you could [add a ref to the child component](#adding-a-ref-to-a-class-component), this is not an ideal solution, as you would only get a component instance rather than a DOM node. Additionally, this wouldn't work with function components.
195
+
Mặc dù bạn có thể [thêm ref vào component con](#adding-a-ref-to-a-class-component), tuy nhiên đây cũng không phải là một ý tưởng tốt, vì cái bạn nhận được chỉ là một component instance chứ không phải là một DOM node. Ý tưởng này cũng sẽ không hoạt động với function components.
197
196
198
-
If you use React 16.3 or higher, we recommend to use [ref forwarding](/docs/forwarding-refs.html)for these cases. **Ref forwarding lets components opt into exposing any child component's ref as their own**. You can find a detailed example of how to expose a child's DOM node to a parent component [in the ref forwarding documentation](/docs/forwarding-refs.html#forwarding-refs-to-dom-components).
197
+
Nếu bạn sử dụng React 16.3 hoặc các phiên bản mới hơn, chúng tôi gợi ý bạn sử dụng [ref forwarding](/docs/forwarding-refs.html)cho những trường hợp như thế này. **Ref forwarding cho phép các component tham gia hiển thị bất kỳ bản tham chiếu nào của component là con của nó**. Bạn có thể tìm hiểu chi tiết thông qua các ví dụ cách component cha hiển thị DOM node con của nó [tại ref forwarding documentation](/docs/forwarding-refs.html#forwarding-refs-to-dom-components).
199
198
200
-
If you use React 16.2 or lower, or if you need more flexibility than provided by ref forwarding, you can use [this alternative approach](https://gist.github.com/gaearon/1a018a023347fe1c2476073330cc5509)and explicitly pass a ref as a differently named prop.
199
+
Nếu bạn sử dụng React 16.2 hoặc các phiên bản thấp hơn, hoặc nếu bạn cần sự linh hoạt hơn được cung cấp bởi ref forwarding, bạn có thể sử dụng [cách tiếp cận thay thể này](https://gist.github.com/gaearon/1a018a023347fe1c2476073330cc5509)và chuyển một tham chiếu dưới dạng tên một prop khác.
201
200
202
-
When possible, we advise against exposing DOM nodes, but it can be a useful escape hatch. Note that this approach requires you to add some code to the child component. If you have absolutely no control over the child component implementation, your last option is to use [`findDOMNode()`](/docs/react-dom.html#finddomnode), but it is discouraged and deprecated in[`StrictMode`](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage).
201
+
Khi có thể, chúng tôi khuyên bạn tránh để lộ các DOM node. Lưu ý rằng cách tiếp cận này yêu cầu bạn thêm một số đoạn code vào component con. Nếu bạn hoàn toàn không kiểm soát được việc triển khai thành phần con, lựa chọn cuối của bạn là sử dụng [`findDOMNode()`](/docs/react-dom.html#finddomnode), nhưng nó không được khuyến khích và không được chấp nhận trong[`StrictMode`](/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage).
203
202
204
203
### Callback Refs {#callback-refs}
205
204
206
-
React also supports another way to set refs called "callback refs", which gives more fine-grain control over when refs are set and unset.
205
+
React cũng hỗ trợ một cách set refs khác gọi là "callback refs", giúp kiểm soát tốt hơn khi set và unset ref.
207
206
208
-
Instead of passing a `ref`attribute created by`createRef()`, you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.
207
+
Thay vì chuyển thuộc tính `ref`được tạo từ`createRef()`, bạn chuyển nó thành một function. Function này sẽ nhận vào một React component instance hoặc HTML DOM element như một argument của nó, có thể được lưu trữ và truy cập ở một nơi khác.
209
208
210
-
The example below implements a common pattern: using the `ref` callback to store a reference to a DOM node in an instance property.
209
+
Ví dụ dưới đây thực hiện việc sử dụng một `ref` callback để lưu trữ tham chiếu tới một DOM node trong một thuộc tính instance.
211
210
212
211
```javascript{5,7-9,11-14,19,29,34}
213
212
class CustomTextInput extends React.Component {
@@ -251,9 +250,9 @@ class CustomTextInput extends React.Component {
251
250
}
252
251
```
253
252
254
-
React will call the `ref` callback with the DOM element when the component mounts, and call it with `null`when it unmounts. Refs are guaranteed to be up-to-date before `componentDidMount`or`componentDidUpdate`fires.
253
+
React sẽ gọi `ref` callback với DOM element khi component mounts, và gọi `null`khi component unmounts. Refs đảm bảo được cập nhật trước khi `componentDidMount`hoặc`componentDidUpdate`khởi chạy.
255
254
256
-
You can pass callback refs between components like you can with object refs that were created with`React.createRef()`.
255
+
Bạn có thể chuyển callback refs giữa những component giống như các đối tượng tham chiếu được tạo bởi`React.createRef()`.
257
256
258
257
```javascript{4,13}
259
258
function CustomTextInput(props) {
@@ -275,16 +274,16 @@ class Parent extends React.Component {
275
274
}
276
275
```
277
276
278
-
In the example above, `Parent`passes its ref callback as an `inputRef` prop to the `CustomTextInput`, and the `CustomTextInput`passes the same function as a special `ref`attribute to the `<input>`. As a result, `this.inputElement`in`Parent`will be set to the DOM node corresponding to the`<input>` element in the`CustomTextInput`.
277
+
Trong ví dụ trên, `Parent`sẽ chuyển ref callback dưới dạng một `inputRef` prop tới `CustomTextInput`, và `CustomTextInput`chuyển một function tương tự như một thuộc tính `ref`tới `<input>`. Lúc đó `this.inputElement`ở`Parent`sẽ set DOM node tương ứng với`<input>` element trong`CustomTextInput`.
If you worked with React before, you might be familiar with an older API where the `ref`attribute is a string, like`"textInput"`, and the DOM node is accessed as `this.refs.textInput`. We advise against it because string refs have [some issues](https://github.com/facebook/react/pull/8333#issuecomment-271648615), are considered legacy, and**are likely to be removed in one of the future releases**.
281
+
Nếu bạn đã làm việc với React trước đây, bạn có thể quen thuộc với một API cũ hơn trong đó thuộc tính `ref`là một String, như`"textInput"`, và DOM node được truy cập bằng `this.refs.textInput`. Chúng tôi khuyên bạn nên tránh sử dụng nó vì string refs có [một vài vấn đề](https://github.com/facebook/react/pull/8333#issuecomment-271648615), liên quan đến kế thừa, và**có khả năng bị xóa trong các bản phát hành tiếp theo.**.
283
282
284
-
> Note
283
+
> Lưu ý
285
284
>
286
-
> If you're currently using `this.refs.textInput`to access refs, we recommend using either the [callback pattern](#callback-refs)or the [`createRef` API](#creating-refs)instead.
285
+
> Nếu hiên tại bạn đang sử dụng `this.refs.textInput`để truy cập đến refs, chúng tôi khuyên bạn nên sử dụng [callback pattern](#callback-refs)hoặc [`createRef` API](#creating-refs)để thay thế.
287
286
288
-
### Caveats with callback refs {#caveats-with-callback-refs}
287
+
### Cảnh báo với callback refs {#caveats-with-callback-refs}
289
288
290
-
If the `ref` callback is defined as an inline function, it will get called twice during updates, first with `null`and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the `ref` callback as a bound method on the class, but note that it shouldn't matter in most cases.
289
+
Nếu `ref` callback được định nghĩa như một inline function, nó sẽ được gọi 2 lần khi cập nhật, lần thứ 1 có giá trị là `null`và lần thứ 2 là DOM element. Điều này xảy ra bởi vì một instance của function được tạo ra sau mỗi lần render, React cần phải xóa những ref cũ và set up một cái mới. Bạn có thể tránh điều này bằng cách định nghĩa `ref` callback như một method trên class, nhưng nó cũng không quan trọng trong hầu hết các trường hợp.
0 commit comments