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: src/content/reference/eslint-plugin-react-hooks/lints/refs.md
+31-31Lines changed: 31 additions & 31 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,83 +4,83 @@ title: refs
4
4
5
5
<Intro>
6
6
7
-
Validates correct usage of refs, not reading/writing during render. See the "pitfalls" section in[`useRef()` usage](/reference/react/useRef#usage).
7
+
Valida o uso correto de refs, não lendo/escrevendo durante a renderização. Veja a seção "armadilhas" em[`useRef()` usage](/reference/react/useRef#usage).
8
8
9
9
</Intro>
10
10
11
-
## Rule Details {/*rule-details*/}
11
+
## Detalhes da Regra {/*rule-details*/}
12
12
13
-
Refs hold values that aren't used for rendering. Unlike state, changing a ref doesn't trigger a re-render. Reading or writing`ref.current`during render breaks React's expectations. Refs might not be initialized when you try to read them, and their values can be stale or inconsistent.
13
+
Refs armazenam valores que não são usados para renderização. Diferente do estado, alterar uma ref não dispara uma nova renderização. Ler ou escrever`ref.current`durante a renderização quebra as expectativas do React. Refs podem não estar inicializadas quando você tenta lê-las, e seus valores podem estar desatualizados ou inconsistentes.
14
14
15
-
## How It Detects Refs {/*how-it-detects-refs*/}
15
+
## Como Detecta Refs {/*how-it-detects-refs*/}
16
16
17
-
The lint only applies these rules to values it knows are refs. A value is inferred as a ref when the compiler sees any of the following patterns:
17
+
A lint aplica estas regras apenas a valores que ela sabe serem refs. Um valor é inferido como ref quando o compilador vê qualquer um dos seguintes padrões:
18
18
19
-
-Returned from`useRef()`or`React.createRef()`.
19
+
-Retornado de`useRef()`ou`React.createRef()`.
20
20
21
21
```js
22
22
constscrollRef=useRef(null);
23
23
```
24
24
25
-
-An identifier named`ref`or ending in `Ref`that reads from or writes to`.current`.
25
+
-Um identificador chamado`ref`ou que termina em `Ref`que lê ou escreve em`.current`.
26
26
27
27
```js
28
28
buttonRef.current= node;
29
29
```
30
30
31
-
-Passed through a JSX `ref`prop (for example`<div ref={someRef} />`).
31
+
-Passado através de uma prop `ref`JSX (por exemplo`<div ref={someRef} />`).
32
32
33
33
```jsx
34
34
<input ref={inputRef} />
35
35
```
36
36
37
-
Once something is marked as a ref, that inference follows the value through assignments, destructuring, or helper calls. This lets the lint surface violations even when`ref.current`is accessed inside another function that received the ref as an argument.
37
+
Uma vez que algo é marcado como ref, essa inferência segue o valor através de atribuições, desestruturação ou chamadas de funções auxiliares. Isso permite que a lint aponte violações mesmo quando`ref.current`é acessado dentro de outra função que recebeu a ref como argumento.
38
38
39
-
## Common Violations {/*common-violations*/}
39
+
## Violações Comuns {/*common-violations*/}
40
40
41
-
-Reading`ref.current`during render
42
-
-Updating`refs`during render
43
-
-Using`refs`for values that should be state
41
+
-Lendo`ref.current`durante a renderização
42
+
-Atualizando`refs`durante a renderização
43
+
-Usando`refs`para valores que deveriam ser estado
44
44
45
-
### Invalid {/*invalid*/}
45
+
### Inválido {/*invalid*/}
46
46
47
-
Examples of incorrect code for this rule:
47
+
Exemplos de código incorreto para esta regra:
48
48
49
49
```js
50
-
// ❌ Reading ref during render
50
+
// ❌ Lendo ref durante a renderização
51
51
functionComponent() {
52
52
constref=useRef(0);
53
-
constvalue=ref.current; //Don't read during render
53
+
constvalue=ref.current; //Não leia durante a renderização
54
54
return<div>{value}</div>;
55
55
}
56
56
57
-
// ❌ Modifying ref during render
57
+
// ❌ Modificando ref durante a renderização
58
58
functionComponent({value}) {
59
59
constref=useRef(null);
60
-
ref.current= value; //Don't modify during render
60
+
ref.current= value; //Não modifique durante a renderização
61
61
return<div />;
62
62
}
63
63
```
64
64
65
-
### Valid {/*valid*/}
65
+
### Válido {/*valid*/}
66
66
67
-
Examples of correct code for this rule:
67
+
Exemplos de código correto para esta regra:
68
68
69
69
```js
70
-
// ✅ Read ref in effects/handlers
70
+
// ✅ Leia ref em efeitos/manipuladores
71
71
functionComponent() {
72
72
constref=useRef(null);
73
73
74
74
useEffect(() => {
75
75
if (ref.current) {
76
-
console.log(ref.current.offsetWidth); // OK in effect
76
+
console.log(ref.current.offsetWidth); // OK no efeito
77
77
}
78
78
});
79
79
80
80
return<div ref={ref} />;
81
81
}
82
82
83
-
// ✅ Use state for UI values
83
+
// ✅ Use estado para valores de UI
84
84
functionComponent() {
85
85
const [count, setCount] =useState(0);
86
86
@@ -91,25 +91,25 @@ function Component() {
91
91
);
92
92
}
93
93
94
-
// ✅ Lazy initialization of ref value
94
+
// ✅ Inicialização preguiçosa do valor da ref
95
95
functionComponent() {
96
96
constref=useRef(null);
97
97
98
-
//Initialize only once on first use
98
+
//Inicializa apenas uma vez no primeiro uso
99
99
if (ref.current===null) {
100
-
ref.current=expensiveComputation(); // OK - lazy initialization
100
+
ref.current=expensiveComputation(); // OK - inicialização preguiçosa
101
101
}
102
102
103
103
consthandleClick= () => {
104
-
console.log(ref.current); // Use the initialized value
104
+
console.log(ref.current); // Use o valor inicializado
### The lint flagged my plain object with`.current` {/*plain-object-current*/}
113
+
### A lint sinalizou meu objeto simples com`.current` {/*plain-object-current*/}
114
114
115
-
The name heuristic intentionally treats `ref.current`and`fooRef.current`as real refs. If you're modeling a custom container object, pick a different name (for example, `box`) or move the mutable value into state. Renaming avoids the lint because the compiler stops inferring it as a ref.
115
+
A heurística de nome intencionalmente trata `ref.current`e`fooRef.current`como refs reais. Se você está modelando um objeto contêiner personalizado, escolha um nome diferente (por exemplo, `box`) ou mova o valor mutável para o estado. Renomear evita a lint porque o compilador para de inferi-lo como uma ref.
0 commit comments