From 76d50c8a642b560654246ae376d1be8459240685 Mon Sep 17 00:00:00 2001 From: Nivaldo Farias Date: Mon, 20 Jan 2025 17:16:19 -0300 Subject: [PATCH] Translate `useRef.md` to pt-br --- src/content/reference/react/useRef.md | 326 +++++++++++++------------- 1 file changed, 163 insertions(+), 163 deletions(-) diff --git a/src/content/reference/react/useRef.md b/src/content/reference/react/useRef.md index fcecae714..5c47cfce8 100644 --- a/src/content/reference/react/useRef.md +++ b/src/content/reference/react/useRef.md @@ -4,10 +4,10 @@ title: useRef -`useRef` is a React Hook that lets you reference a value that's not needed for rendering. +`useRef` é um Hook do React que permite referenciar um valor que não é necessário para renderização. ```js -const ref = useRef(initialValue) +const ref = useRef(valorInicial) ``` @@ -16,112 +16,112 @@ const ref = useRef(initialValue) --- -## Reference {/*reference*/} +## Referência {/*reference*/} -### `useRef(initialValue)` {/*useref*/} +### `useRef(valorInicial)` {/*useref*/} -Call `useRef` at the top level of your component to declare a [ref.](/learn/referencing-values-with-refs) +Chame `useRef` na raiz do seu componente para declarar um [ref.](/learn/referencing-values-with-refs) ```js import { useRef } from 'react'; -function MyComponent() { - const intervalRef = useRef(0); - const inputRef = useRef(null); +function MeuComponente() { + const intervaloRef = useRef(0); + const entradaRef = useRef(null); // ... ``` -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*parameters*/} +#### Parâmetros {/*parameters*/} -* `initialValue`: The value you want the ref object's `current` property to be initially. It can be a value of any type. This argument is ignored after the initial render. +* `valorInicial`: O valor que você deseja que a propriedade `current` do objeto ref seja inicialmente. Pode ser um valor de qualquer tipo. Este argumento é ignorado após a renderização inicial. -#### Returns {/*returns*/} +#### Retornos {/*returns*/} -`useRef` returns an object with a single property: +`useRef` retorna um objeto com uma única propriedade: -* `current`: Initially, it's set to the `initialValue` you have passed. You can later set it to something else. If you pass the ref object to React as a `ref` attribute to a JSX node, React will set its `current` property. +* `current`: Inicialmente, é definido como o `valorInicial` que você passou. Você pode defini-lo posteriormente para algo diferente. Se você passar o objeto ref para o React como um atributo `ref` para um nó JSX, o React definirá sua propriedade `current`. -On the next renders, `useRef` will return the same object. +Nas próximas renderizações, `useRef` retornará o mesmo objeto. -#### Caveats {/*caveats*/} +#### Ressalvas {/*caveats*/} -* You can mutate the `ref.current` property. Unlike state, it is mutable. However, if it holds an object that is used for rendering (for example, a piece of your state), then you shouldn't mutate that object. -* When you change the `ref.current` property, React does not re-render your component. React is not aware of when you change it because a ref is a plain JavaScript object. -* Do not write _or read_ `ref.current` during rendering, except for [initialization.](#avoiding-recreating-the-ref-contents) This makes your component's behavior unpredictable. -* In Strict Mode, React will **call your component function twice** in order to [help you find accidental impurities.](/reference/react/useState#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. Each ref object will be created twice, but one of the versions will be discarded. If your component function is pure (as it should be), this should not affect the behavior. +* Você pode modificar a propriedade `ref.current`. Ao contrário do estado, é mutável. No entanto, se ele contiver um objeto que é usado para renderização (por exemplo, uma parte do seu estado), você não deve modificar esse objeto. +* Quando você muda a propriedade `ref.current`, o React não re-renderiza seu componente. O React não está ciente de quando você a altera, pois um ref é um objeto JavaScript simples. +* Não escreva _ou leia_ `ref.current` durante a renderização, exceto para [inicialização.](#avoiding-recreating-the-ref-contents) Isso torna o comportamento do seu componente imprevisível. +* No Modo Estrito, o React **chamará a função do seu componente duas vezes** a fim de [ajudá-lo a encontrar impurezas acidentais.](/reference/react/useState#my-initializer-or-updater-function-runs-twice) Este é um comportamento exclusivo de desenvolvimento e não afeta a produção. Cada objeto ref será criado duas vezes, mas uma das versões será descartada. Se a função do seu componente for pura (como deveria ser), isso não deve afetar o comportamento. --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Referencing a value with a ref {/*referencing-a-value-with-a-ref*/} +### Referenciando um valor com um ref {/*referencing-a-value-with-a-ref*/} -Call `useRef` at the top level of your component to declare one or more [refs.](/learn/referencing-values-with-refs) +Chame `useRef` na raiz do seu componente para declarar um ou mais [refs.](/learn/referencing-values-with-refs) ```js [[1, 4, "intervalRef"], [3, 4, "0"]] import { useRef } from 'react'; -function Stopwatch() { - const intervalRef = useRef(0); +function Cronômetro() { + const intervaloRef = useRef(0); // ... ``` -`useRef` returns a ref object with a single `current` property initially set to the initial value you provided. +`useRef` retorna um objeto ref com uma única propriedade `current` inicialmente definida como o valor inicial que você forneceu. -On the next renders, `useRef` will return the same object. You can change its `current` property to store information and read it later. This might remind you of [state](/reference/react/useState), but there is an important difference. +Nas próximas renderizações, `useRef` retornará o mesmo objeto. Você pode alterar sua propriedade `current` para armazenar informações e lê-las depois. Isso pode lembrá-lo do [estado](/reference/react/useState), mas há uma diferença importante. -**Changing a ref does not trigger a re-render.** This means refs are perfect for storing information that doesn't affect the visual output of your component. For example, if you need to store an [interval ID](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) and retrieve it later, you can put it in a ref. To update the value inside the ref, you need to manually change its `current` property: +**Mudar um ref não dispara uma re-renderização.** Isso significa que os refs são perfeitos para armazenar informações que não afetam a saída visual do seu componente. Por exemplo, se você precisar armazenar um [ID de intervalo](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) e recuperá-lo mais tarde, você pode colocá-lo em um ref. Para atualizar o valor dentro do ref, você precisa mudar manualmente sua propriedade `current`: ```js [[2, 5, "intervalRef.current"]] function handleStartClick() { const intervalId = setInterval(() => { // ... }, 1000); - intervalRef.current = intervalId; + intervaloRef.current = intervalId; } ``` -Later, you can read that interval ID from the ref so that you can call [clear that interval](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval): +Mais tarde, você pode ler esse ID de intervalo do ref para que possa [limpar esse intervalo](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval): ```js [[2, 2, "intervalRef.current"]] function handleStopClick() { - const intervalId = intervalRef.current; + const intervalId = intervaloRef.current; clearInterval(intervalId); } ``` -By using a ref, you ensure that: +Ao usar um ref, você garante que: -- You can **store information** between re-renders (unlike regular variables, which reset on every render). -- Changing it **does not trigger a re-render** (unlike state variables, which trigger a re-render). -- The **information is local** to each copy of your component (unlike the variables outside, which are shared). +- Você pode **armazenar informações** entre as re-renderizações (diferente de variáveis regulares, que se resetam em cada render). +- Mudá-lo **não dispara uma re-renderização** (diferente de variáveis de estado, que disparam uma re-renderização). +- A **informação é local** para cada cópia do seu componente (diferente de variáveis fora, que são compartilhadas). -Changing a ref does not trigger a re-render, so refs are not appropriate for storing information you want to display on the screen. Use state for that instead. Read more about [choosing between `useRef` and `useState`.](/learn/referencing-values-with-refs#differences-between-refs-and-state) +Mudar um ref não dispara uma re-renderização, então refs não são apropriados para armazenar informações que você deseja exibir na tela. Use estado para isso em vez disso. Leia mais sobre [escolher entre `useRef` e `useState`.](/learn/referencing-values-with-refs#differences-between-refs-and-state) - + -#### Click counter {/*click-counter*/} +#### Contador de cliques {/*click-counter*/} -This component uses a ref to keep track of how many times the button was clicked. Note that it's okay to use a ref instead of state here because the click count is only read and written in an event handler. +Esse componente usa um ref para acompanhar quantas vezes o botão foi clicado. Note que é aceitável usar um ref em vez de estado aqui porque a contagem de cliques é apenas lida e escrita em um manipulador de eventos. ```js import { useRef } from 'react'; -export default function Counter() { +export default function Contador() { let ref = useRef(0); function handleClick() { ref.current = ref.current + 1; - alert('You clicked ' + ref.current + ' times!'); + alert('Você clicou ' + ref.current + ' vezes!'); } return ( ); } @@ -129,51 +129,51 @@ export default function Counter() { -If you show `{ref.current}` in the JSX, the number won't update on click. This is because setting `ref.current` does not trigger a re-render. Information that's used for rendering should be state instead. +Se você mostrar `{ref.current}` no JSX, o número não será atualizado ao clicar. Isso ocorre porque definir `ref.current` não dispara uma re-renderização. Informações que são usadas para renderização devem ser estado em vez disso. - + -#### A stopwatch {/*a-stopwatch*/} +#### Um cronômetro {/*a-stopwatch*/} -This example uses a combination of state and refs. Both `startTime` and `now` are state variables because they are used for rendering. But we also need to hold an [interval ID](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) so that we can stop the interval on button press. Since the interval ID is not used for rendering, it's appropriate to keep it in a ref, and manually update it. +Este exemplo usa uma combinação de estado e refs. Tanto `startTime` quanto `now` são variáveis de estado porque são usadas para renderização. Mas também precisamos armazenar um [ID de intervalo](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) para que possamos parar o intervalo ao pressionar o botão. Como o ID de intervalo não é usado para renderização, é apropriado mantê-lo em um ref e atualizá-lo manualmente. ```js import { useState, useRef } from 'react'; -export default function Stopwatch() { - const [startTime, setStartTime] = useState(null); - const [now, setNow] = useState(null); - const intervalRef = useRef(null); +export default function Cronômetro() { + const [inicioTempo, setInicioTempo] = useState(null); + const [agora, setAgora] = useState(null); + const intervaloRef = useRef(null); function handleStart() { - setStartTime(Date.now()); - setNow(Date.now()); + setInicioTempo(Date.now()); + setAgora(Date.now()); - clearInterval(intervalRef.current); - intervalRef.current = setInterval(() => { - setNow(Date.now()); + clearInterval(intervaloRef.current); + intervaloRef.current = setInterval(() => { + setAgora(Date.now()); }, 10); } function handleStop() { - clearInterval(intervalRef.current); + clearInterval(intervaloRef.current); } - let secondsPassed = 0; - if (startTime != null && now != null) { - secondsPassed = (now - startTime) / 1000; + let segundosPassados = 0; + if (inicioTempo != null && agora != null) { + segundosPassados = (agora - inicioTempo) / 1000; } return ( <> -

Time passed: {secondsPassed.toFixed(3)}

+

Tempo decorrido: {segundosPassados.toFixed(3)}

); @@ -182,96 +182,96 @@ export default function Stopwatch() {
- + -
+ - + -**Do not write _or read_ `ref.current` during rendering.** +**Não escreva _ou leia_ `ref.current` durante a renderização.** -React expects that the body of your component [behaves like a pure function](/learn/keeping-components-pure): +O React espera que o corpo do seu componente [comporte-se como uma função pura](/learn/keeping-components-pure): -- If the inputs ([props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), and [context](/learn/passing-data-deeply-with-context)) are the same, it should return exactly the same JSX. -- Calling it in a different order or with different arguments should not affect the results of other calls. +- Se as entradas ([props](/learn/passing-props-to-a-component), [estado](/learn/state-a-components-memory), e [contexto](/learn/passing-data-deeply-with-context)) forem as mesmas, deve retornar exatamente o mesmo JSX. +- Chamá-lo em uma ordem diferente ou com argumentos diferentes não deve afetar os resultados de outras chamadas. -Reading or writing a ref **during rendering** breaks these expectations. +Ler ou escrever um ref **durante a renderização** quebra essas expectativas. ```js {3-4,6-7} -function MyComponent() { +function MeuComponente() { // ... - // 🚩 Don't write a ref during rendering - myRef.current = 123; + // 🚩 Não escreva um ref durante a renderização + meuRef.current = 123; // ... - // 🚩 Don't read a ref during rendering - return

{myOtherRef.current}

; + // 🚩 Não leia um ref durante a renderização + return

{meuOutroRef.current}

; } ``` -You can read or write refs **from event handlers or effects instead**. +Você pode ler ou escrever refs **a partir de manipuladores de eventos ou efeitos**. ```js {4-5,9-10} -function MyComponent() { +function MeuComponente() { // ... useEffect(() => { - // ✅ You can read or write refs in effects - myRef.current = 123; + // ✅ Você pode ler ou escrever refs em efeitos + meuRef.current = 123; }); // ... function handleClick() { - // ✅ You can read or write refs in event handlers - doSomething(myOtherRef.current); + // ✅ Você pode ler ou escrever refs em manipuladores de eventos + fazerAlgo(meuOutroRef.current); } // ... } ``` -If you *have to* read [or write](/reference/react/useState#storing-information-from-previous-renders) something during rendering, [use state](/reference/react/useState) instead. +Se você *precisar* ler [ou escrever](/reference/react/useState#storing-information-from-previous-renders) algo durante a renderização, use [estado](/reference/react/useState) em vez disso. -When you break these rules, your component might still work, but most of the newer features we're adding to React will rely on these expectations. Read more about [keeping your components pure.](/learn/keeping-components-pure#where-you-_can_-cause-side-effects) +Quando você quebra essas regras, seu componente ainda pode funcionar, mas a maioria dos novos recursos que estamos adicionando ao React dependerão dessas expectativas. Leia mais sobre [manter seus componentes puros.](/learn/keeping-components-pure#where-you-_can_-cause-side-effects) -
+ --- -### Manipulating the DOM with a ref {/*manipulating-the-dom-with-a-ref*/} +### Manipulando o DOM com um ref {/*manipulating-the-dom-with-a-ref*/} -It's particularly common to use a ref to manipulate the [DOM.](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API) React has built-in support for this. +É particularmente comum usar um ref para manipular o [DOM.](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API) O React tem suporte embutido para isso. -First, declare a ref object with an initial value of `null`: +Primeiro, declare um objeto ref com um valor inicial de `null`: ```js [[1, 4, "inputRef"], [3, 4, "null"]] import { useRef } from 'react'; -function MyComponent() { - const inputRef = useRef(null); +function MeuComponente() { + const entradaRef = useRef(null); // ... ``` -Then pass your ref object as the `ref` attribute to the JSX of the DOM node you want to manipulate: +Em seguida, passe seu objeto ref como o atributo `ref` para o JSX do nó DOM que você deseja manipular: ```js [[1, 2, "inputRef"]] // ... - return ; + return ; ``` -After React creates the DOM node and puts it on the screen, React will set the `current` property of your ref object to that DOM node. Now you can access the ``'s DOM node and call methods like [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus): +Depois que o React cria o nó DOM e o coloca na tela, o React definirá a propriedade `current` do seu objeto ref para aquele nó DOM. Agora você pode acessar o nó DOM do `` e chamar métodos como [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus): ```js [[2, 2, "inputRef.current"]] function handleClick() { - inputRef.current.focus(); + entradaRef.current.focus(); } ``` -React will set the `current` property back to `null` when the node is removed from the screen. +O React definirá a propriedade `current` de volta para `null` quando o nó for removido da tela. -Read more about [manipulating the DOM with refs.](/learn/manipulating-the-dom-with-refs) +Leia mais sobre [manipulando o DOM com refs.](/learn/manipulating-the-dom-with-refs) - + -#### Focusing a text input {/*focusing-a-text-input*/} +#### Focando em um campo de texto {/*focusing-a-text-input*/} -In this example, clicking the button will focus the input: +Neste exemplo, clicar no botão irá focar o campo de entrada: @@ -279,17 +279,17 @@ In this example, clicking the button will focus the input: import { useRef } from 'react'; export default function Form() { - const inputRef = useRef(null); + const entradaRef = useRef(null); function handleClick() { - inputRef.current.focus(); + entradaRef.current.focus(); } return ( <> - + ); @@ -298,25 +298,25 @@ export default function Form() { - + -#### Scrolling an image into view {/*scrolling-an-image-into-view*/} +#### Rolando uma imagem para visualizar {/*scrolling-an-image-into-view*/} -In this example, clicking the button will scroll an image into view. It uses a ref to the list DOM node, and then calls DOM [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) API to find the image we want to scroll to. +Neste exemplo, clicar no botão rolará uma imagem para visualizar. Ele usa um ref para o nó DOM da lista e, em seguida, chama a API DOM [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) para encontrar a imagem que desejamos rolar. ```js import { useRef } from 'react'; -export default function CatFriends() { - const listRef = useRef(null); +export default function AmigosGato() { + const listaRef = useRef(null); - function scrollToIndex(index) { - const listNode = listRef.current; - // This line assumes a particular DOM structure: - const imgNode = listNode.querySelectorAll('li > img')[index]; - imgNode.scrollIntoView({ + function rolarParaIndice(indice) { + const nóLista = listaRef.current; + // Esta linha assume uma estrutura DOM particular: + const nóImg = nóLista.querySelectorAll('li > img')[indice]; + nóImg.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' @@ -326,18 +326,18 @@ export default function CatFriends() { return ( <>
-
    +
    • - + -#### Playing and pausing a video {/*playing-and-pausing-a-video*/} +#### Reproduzindo e pausando um vídeo {/*playing-and-pausing-a-video*/} -This example uses a ref to call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on a `