Skip to content

Commit c9bd741

Browse files
[FEAT]: Translate useImperativeHandle page to pt-br (#727)
1 parent 394bd56 commit c9bd741

File tree

1 file changed

+30
-26
lines changed

1 file changed

+30
-26
lines changed

src/content/reference/react/useImperativeHandle.md

+30-26
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: useImperativeHandle
44

55
<Intro>
66

7-
`useImperativeHandle` is a React Hook that lets you customize the handle exposed as a [ref.](/learn/manipulating-the-dom-with-refs)
7+
`useImperativeHandle` é um React Hook que permite customizar o identificador exposto como [ref.](/learn/manipulating-the-dom-with-refs)
88

99
```js
1010
useImperativeHandle(ref, createHandle, dependencies?)
@@ -16,45 +16,46 @@ useImperativeHandle(ref, createHandle, dependencies?)
1616
1717
---
1818
19-
## Reference {/*reference*/}
19+
## Referência {/*reference*/}
2020
2121
### `useImperativeHandle(ref, createHandle, dependencies?)` {/*useimperativehandle*/}
2222
23-
Call `useImperativeHandle` at the top level of your component to customize the ref handle it exposes:
23+
Chame `useImperativeHandle` no nível superior do seu componente para customizar o identificador de referência que ele expõe:
2424
2525
```js
2626
import { forwardRef, useImperativeHandle } from 'react';
2727

2828
const MyInput = forwardRef(function MyInput(props, ref) {
2929
useImperativeHandle(ref, () => {
3030
return {
31-
// ... your methods ...
31+
// ... seus métodos ...
3232
};
3333
}, []);
3434
// ...
3535
```
3636
37-
[See more examples below.](#usage)
37+
[Veja mais exemplos abaixo.](#usage)
3838
39-
#### Parameters {/*parameters*/}
39+
#### Parâmetros {/*parameters*/}
4040
41-
* `ref`: The `ref` you received as the second argument from the [`forwardRef` render function.](/reference/react/forwardRef#render-function)
41+
* `ref`: A `ref` que você recebeu como segundo argumento da [função de renderização `forwardRef`.](/reference/react/forwardRef#render-function)
4242
43-
* `createHandle`: A function that takes no arguments and returns the ref handle you want to expose. That ref handle can have any type. Usually, you will return an object with the methods you want to expose.
43+
* `createHandle`: Uma função que não aceita argumentos e retorna o identificador de referência que você deseja expor. Essa identificador de referência pode ter qualquer tipo. Normalmente, você retornará um objeto com os métodos que deseja expor.
4444
45-
* **optional** `dependencies`: The list of all reactive values referenced inside of the `createHandle` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. If a re-render resulted in a change to some dependency, or if you omitted this argument, your `createHandle` function will re-execute, and the newly created handle will be assigned to the ref.
45+
* **opcional** `dependencies`: A lista de todos os valores reativos referenciados dentro do código `createHandle`. Os valores reativos incluem propriedades, estado, e todas as variáveis e funções declaradas diretamente dentro do corpo do seu componente. Se o seu linter estiver [configurado para React](/learn/editor-setup#linting), ele verificará se cada valor reativo está especificado corretamente como uma dependência. A lista de dependências devem ter um número constante de items e ser escrito inline como `[dep1, dep2, dep3]`. O React comparará cada dependência com seu valor anterior usando a comparação [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Se uma nova renderização resultou em uma alteração em alguma dependência, ou se você omitiu este argumento, sua função `createHandle` será executada novamente e o identificador recém-criado será atribuído à ref.
4646
47-
#### Returns {/*returns*/}
47+
#### Retorna {/*returns*/}
4848
49-
`useImperativeHandle` returns `undefined`.
49+
`useImperativeHandle` retorna `undefined`.
5050
5151
---
5252
53-
## Usage {/*usage*/}
53+
## Uso {/*usage*/}
5454
55-
### Exposing a custom ref handle to the parent component {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
55+
### Expondo um identificador de referência customizado ao componente pai {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
56+
57+
Por padrão, os componentes não expõem seus nós DOM aos componentes pai. Por exemplo, se você deseja que o componente pai de `MyInput` [tenha acesso](/learn/manipulating-the-dom-with-refs) ao nó DOM `<input>`, você deve optar por [`forwardRef`:](/referência/react/forwardRef)
5658
57-
By default, components don't expose their DOM nodes to parent components. For example, if you want the parent component of `MyInput` to [have access](/learn/manipulating-the-dom-with-refs) to the `<input>` DOM node, you have to opt in with [`forwardRef`:](/reference/react/forwardRef)
5859
5960
```js {4}
6061
import { forwardRef } from 'react';
@@ -64,25 +65,26 @@ const MyInput = forwardRef(function MyInput(props, ref) {
6465
});
6566
```
6667
67-
With the code above, [a ref to `MyInput` will receive the `<input>` DOM node.](/reference/react/forwardRef#exposing-a-dom-node-to-the-parent-component) However, you can expose a custom value instead. To customize the exposed handle, call `useImperativeHandle` at the top level of your component:
68+
Com o código acima, [uma referência para `MyInput` receberá o nó DOM `<input>`.](/reference/react/forwardRef#exposing-a-dom-node-to-the-parent-component) No entanto, você pode expor um valor customizado. Para customizar o identificador exposto, chame `useImperativeHandle` no nível superior do seu componente:
6869
6970
```js {4-8}
7071
import { forwardRef, useImperativeHandle } from 'react';
7172

7273
const MyInput = forwardRef(function MyInput(props, ref) {
7374
useImperativeHandle(ref, () => {
7475
return {
75-
// ... your methods ...
76+
// ... seus métodos ...
7677
};
7778
}, []);
7879

7980
return <input {...props} />;
8081
});
8182
```
8283
83-
Note that in the code above, the `ref` is no longer forwarded to the `<input>`.
84+
Note que no código acima, a `ref` não é mais encaminhado para o `<input>`.
85+
86+
Por exemplo, suponha que você não queira expor todo o nó DOM `<input>`, mas você deseja expor dois de seus métodos: `focus` e `scrollIntoView`. Para fazer isso, mantenha o DOM real do navegador em uma referência separada. Em seguida, use `useImperativeHandle` para expor um identificador com apenas os métodos que você deseja que o componente pai chame:
8487
85-
For example, suppose you don't want to expose the entire `<input>` DOM node, but you want to expose two of its methods: `focus` and `scrollIntoView`. To do this, keep the real browser DOM in a separate ref. Then use `useImperativeHandle` to expose a handle with only the methods that you want the parent component to call:
8688
8789
```js {7-14}
8890
import { forwardRef, useRef, useImperativeHandle } from 'react';
@@ -105,7 +107,8 @@ const MyInput = forwardRef(function MyInput(props, ref) {
105107
});
106108
```
107109
108-
Now, if the parent component gets a ref to `MyInput`, it will be able to call the `focus` and `scrollIntoView` methods on it. However, it will not have full access to the underlying `<input>` DOM node.
110+
Agora, se o componente pai obtiver uma referência para `MyInput`, ele será capaz de chamar os métodos `focus` e `scrollIntoView` nele. No entanto, ele não terá acesso total ao nó DOM `<input>` subjacente.
111+
109112
110113
<Sandpack>
111114
@@ -118,7 +121,7 @@ export default function Form() {
118121

119122
function handleClick() {
120123
ref.current.focus();
121-
// This won't work because the DOM node isn't exposed:
124+
// Isso não funcionará porque o nó DOM não está exposto:
122125
// ref.current.style.opacity = 0.5;
123126
}
124127

@@ -166,9 +169,10 @@ input {
166169
167170
---
168171
169-
### Exposing your own imperative methods {/*exposing-your-own-imperative-methods*/}
172+
### Expondo seus próprios métodos imperativos {/*exposing-your-own-imperative-methods*/}
173+
174+
Os métodos que você expõe por meio de um identificador imperativo não precisam corresponder exatamente aos métodos DOM. Por exemplo, este componente `Post` expõe um método `scrollAndFocusAddComment` por meio de um identificador imperativo. Isso permite que a `Page` pai role a lista de comentários *e* foque no campo de entrada quando você clica no botão:
170175
171-
The methods you expose via an imperative handle don't have to match the DOM methods exactly. For example, this `Post` component exposes a `scrollAndFocusAddComment` method via an imperative handle. This lets the parent `Page` scroll the list of comments *and* focus the input field when you click the button:
172176
173177
<Sandpack>
174178
@@ -244,7 +248,7 @@ const CommentList = forwardRef(function CommentList(props, ref) {
244248

245249
let comments = [];
246250
for (let i = 0; i < 50; i++) {
247-
comments.push(<p key={i}>Comment #{i}</p>);
251+
comments.push(<p key={i}>Comentário #{i}</p>);
248252
}
249253

250254
return (
@@ -261,7 +265,7 @@ export default CommentList;
261265
import { forwardRef, useRef, useImperativeHandle } from 'react';
262266

263267
const AddComment = forwardRef(function AddComment(props, ref) {
264-
return <input placeholder="Add comment..." ref={ref} />;
268+
return <input placeholder="Adicionar comentário..." ref={ref} />;
265269
});
266270

267271
export default AddComment;
@@ -281,8 +285,8 @@ export default AddComment;
281285
282286
<Pitfall>
283287
284-
**Do not overuse refs.** You should only use refs for *imperative* behaviors that you can't express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.
288+
**Não abuse das referências.** Você deve apenas usar referências para comportamentos *imperativos* que você não pode expressar como propriedades: por exemplo, rolar até um nó, focar em um nó, disparar uma animação, selecionar texto e assim por diante.
285289
286-
**If you can express something as a prop, you should not use a ref.** For example, instead of exposing an imperative handle like `{ open, close }` from a `Modal` component, it is better to take `isOpen` as a prop like `<Modal isOpen={isOpen} />`. [Effects](/learn/synchronizing-with-effects) can help you expose imperative behaviors via props.
290+
**Se você pode expressar algo como uma propriedade, não deve usar uma referência.** Por exemplo, em vez de expor um identificador imperativo como `{ open, close }` de um componente `Modal`, é melhor usar `isOpen` como um suporte como `<Modal isOpen={isOpen} />`. [Efeitos](/learn/synchronizing-with-effects) podem ajudá-lo a expor comportamentos imperativos por meio de propriedades.
287291
288292
</Pitfall>

0 commit comments

Comments
 (0)