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/render-props.md
+53-48Lines changed: 53 additions & 48 deletions
Original file line number
Diff line number
Diff line change
@@ -4,25 +4,25 @@ title: Render Props
4
4
permalink: docs/render-props.html
5
5
---
6
6
7
-
The term ["render prop"](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce) refers to a technique for sharing code between React components using a prop whose value is a function.
7
+
O termo _["render prop"](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce)_ se refere a uma técnica de compartilhar código entre componentes React passando uma prop cujo valor é uma função.
8
8
9
-
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
9
+
Um componente com uma _render prop_ recebe uma função que retorna um elemento React e a invoca no momento de renderização, não sendo necessário para o componente implementar uma lógica própria.
10
10
11
11
```jsx
12
12
<DataProvider render={data=> (
13
13
<h1>Hello {data.target}</h1>
14
14
)}/>
15
15
```
16
16
17
-
Libraries that use render props include [React Router](https://reacttraining.com/react-router/web/api/Route/Route-render-methods)and[Downshift](https://github.com/paypal/downshift).
17
+
[React Router](https://reacttraining.com/react-router/web/api/Route/Route-render-methods)e[Downshift](https://github.com/paypal/downshift) são exemplos de bibliotecas que utilizam _render props_.
18
18
19
-
In this document, we’ll discuss why render props are useful, and how to write your own.
19
+
Nesse documento vamos discutir por que _render props_ são úteis e como escrevê-las.
20
20
21
-
## Use Render Props for Cross-Cutting Concerns {#use-render-props-for-cross-cutting-concerns}
21
+
## Uso de _Render Props_ para Características Transversais {#use-render-props-for-cross-cutting-concerns}
22
22
23
-
Components are the primary unit of code reuse in React, but it's not always obvious how to share the state or behavior that one component encapsulates to other components that need that same state.
23
+
Componentes são as principais unidades de reuso de código em React, mas nem sempre é fácil compartilhar o estado ou comportamento que um componente encapsula para outros componentes utilizarem esses valores.
24
24
25
-
For example, the following component tracks the mouse position in a web app:
25
+
Por exemplo, o componente abaixo captura a posição do mouse em um aplicativo web:
26
26
27
27
```js
28
28
classMouseTrackerextendsReact.Component {
@@ -50,14 +50,14 @@ class MouseTracker extends React.Component {
50
50
}
51
51
```
52
52
53
-
As the cursor moves around the screen, the component displays its (x, y) coordinates in a `<p>`.
53
+
Enquanto o cursor se move pela tela, o componente mostra suas coordenadas (x, y) em um `<p>`
54
54
55
-
Now the question is: How can we reuse this behavior in another component? In other words, if another component needs to know about the cursor position, can we encapsulate that behavior so that we can easily share it with that component?
55
+
A questão é: Como podemos reutilizar esse comportamento em outro componente? Em outras palavras, se outro componente precisar saber a posição do cursor, podemos encapsular esse comportamento de forma que seja fácil compartilhá-lo com outros componentes?
56
56
57
-
Since components are the basic unit of code reuse in React, let's try refactoring the code a bit to use a `<Mouse>` component that encapsulates the behavior we need to reuse elsewhere.
57
+
Lembrando que componentes são a unidade básica de reuso de código em React, vamos tentar refatorar esse código para usar o componente `<Mouse>`, ele encapsula o comportamento que precisamos reutilizar.
58
58
59
59
```js
60
-
//The <Mouse> component encapsulates the behavior we need...
60
+
//O componente <Mouse> encapsula o comportamento que precisamos...
61
61
classMouseextendsReact.Component {
62
62
constructor(props) {
63
63
super(props);
@@ -76,7 +76,7 @@ class Mouse extends React.Component {
{/* ...but how do we render something other than a <p>? */}
79
+
{/* ...mas como renderizar algo diferente de um <p>? */}
80
80
<p>The current mouse position is ({this.state.x}, {this.state.y})</p>
81
81
</div>
82
82
);
@@ -95,11 +95,12 @@ class MouseTracker extends React.Component {
95
95
}
96
96
```
97
97
98
-
Now the `<Mouse>`component encapsulates all behavior associated with listening for `mousemove`events and storing the (x, y) position of the cursor, but it's not yet truly reusable.
98
+
Agora o componente `<Mouse>`encapsula todos os comportamentos associados aos eventos `mousemove`e guarda a posição (x, y) do cursor, mas ainda não é completamente reutilizável.
99
99
100
-
For example, let's say we have a `<Cat>` component that renders the image of a cat chasing the mouse around the screen. We might use a `<Cat mouse={{ x, y }}>` prop to tell the component the coordinates of the mouse so it knows where to position the image on the screen.
100
+
Por exemplo, suponha que temos o componente `<Cat>` que renderiza a image de um gato seguindo o mouse na tela.
101
+
Poderíamos usar uma _prop_`<Cat mouse={{ x, y }}>` que passaria as coordenadas do mouse para o componente de forma que este saberia onde posicionar a imagem na tela.
101
102
102
-
As a first pass, you might try rendering the `<Cat>`*inside `<Mouse>`'s `render` method*, like this:
103
+
Inicialmente, você poderia tentar renderizar `<Cat>`*dentro do método render do `<Mouse>`*, assim:
103
104
104
105
```js
105
106
classCatextendsReact.Component {
@@ -130,10 +131,10 @@ class MouseWithCat extends React.Component {
We could just swap out the <p> for a <Cat> here ... but then
134
-
we would need to create a separate <MouseWithSomethingElse>
135
-
component every time we need to use it, so <MouseWithCat>
136
-
isn't really reusable yet.
134
+
Poderíamos simplesmente trocar o <p> por um <Cat> ... mas assim
135
+
teríamos que criar um componente <MouseWithSomethingElse>
136
+
separado toda vez que precisarmos usá-lo, então <MouseWithCat>
137
+
não é muito reutilizável ainda.
137
138
*/}
138
139
<Cat mouse={this.state} />
139
140
</div>
@@ -153,9 +154,9 @@ class MouseTracker extends React.Component {
153
154
}
154
155
```
155
156
156
-
This approach will work for our specific use case, but we haven't achieved the objective of truly encapsulating the behavior in a reusable way. Now, every time we want the mouse position for a different use case, we have to create a new component (i.e. essentially another`<MouseWithCat>`) that renders something specifically for that use case.
157
+
Essa abordagem funciona para o nosso caso em específico, mas ainda não atingimos o objetivo de encapsular o comportamento de uma maneira completamente reutilizável. Agora, toda vez que precisarmos da posição do mouse para outro caso, teremos que criar um novo componente (ou seja, outro`<MouseWithCat>`) que renderiza algo especificamente para esse caso.
157
158
158
-
Here's where the render prop comes in: Instead of hard-coding a `<Cat>`inside a`<Mouse>` component, and effectively changing its rendered output, we can provide `<Mouse>` with a function prop that it uses to dynamically determine what to render–a render prop.
159
+
Aqui é onde a _render prop_ se encaixa: Ao invés de escrever um componente `<Cat>`dentro de`<Mouse>`, e mudar diretamente a saída renderizada, podemos passar uma função como prop para `<Mouse>`, que vai chamá-la para determinar o que renderizar dinamicamente- essa é a _render prop_.
159
160
160
161
```js
161
162
classCatextendsReact.Component {
@@ -186,8 +187,9 @@ class Mouse extends React.Component {
Instead of providing a static representation of what <Mouse> renders,
190
-
use the `render` prop to dynamically determine what to render.
190
+
No lugar de fornecer uma representação estática do que <Mouse> deve
191
+
renderizar, use a `render` prop para determinar o que renderizar
192
+
dinamicamente.
191
193
*/}
192
194
{this.props.render(this.state)}
193
195
</div>
@@ -209,17 +211,18 @@ class MouseTracker extends React.Component {
209
211
}
210
212
```
211
213
212
-
Now, instead of effectively cloning the `<Mouse>`component and hard-coding something else in its `render`method to solve for a specific use case, we provide a `render` prop that`<Mouse>`can use to dynamically determine what it renders.
214
+
Agora, no lugar de clonar o componente `<Mouse>`e escrever o método `render`para resolver um caso específico, nós passamos uma _render prop_ que`<Mouse>`pode usar para determinar o que ele renderiza dinamicamente.
213
215
214
-
More concretely, **a render prop is a function prop that a component uses to know what to render.**
216
+
Portanto, **uma _render prop_ é uma função passada nas _props_ que um componente utiliza para determinar o que renderizar.**
215
217
216
-
This technique makes the behavior that we need to share extremely portable. To get that behavior, render a `<Mouse>`with a`render`prop that tells it what to render with the current (x, y) of the cursor.
218
+
Essa técnica torna o comportamento que precisamos compartilhar extremamente portátil. Para acessar esse comportamento, basta renderizar um `<Mouse>`com uma`render`_prop_ que dirá o que renderizar com o (x, y) atual do cursor.
217
219
218
-
One interesting thing to note about render props is that you can implement most [higher-order components](/docs/higher-order-components.html) (HOC) using a regular component with a render prop. For example, if you would prefer to have a `withMouse`HOC instead of a `<Mouse>` component, you could easily create one using a regular `<Mouse>`with a render prop:
220
+
Algo interessante para notar sobre _render props_ é que você pode implementar a maioria dos _[higher-order components](/docs/higher-order-components.html)_ (HOC) utilizando um componente qualquer com uma _render prop_. Por exemplo, se você preferir ter um HOC `withMouse`no lugar de um componente `<Mouse>`, você poderia simplesmente criar um utilizando o `<Mouse>`com uma _render prop_.
219
221
220
222
```js
221
-
// If you really want a HOC for some reason, you can easily
222
-
// create one using a regular component with a render prop!
223
+
// Se você realmente quer usar HOC por alguma razão, você
224
+
// pode facilmente criar uma usando um componente qualquer
225
+
// com uma render prop!
223
226
functionwithMouse(Component) {
224
227
returnclassextendsReact.Component {
225
228
render() {
@@ -233,21 +236,21 @@ function withMouse(Component) {
233
236
}
234
237
```
235
238
236
-
So using a render prop makes it possible to use either pattern.
239
+
Então, utilizar uma _render prop_ torna possível qualquer um dos padrões citados.
237
240
238
-
## Using Props Other Than `render`{#using-props-other-than-render}
241
+
## Usando outras _Props_ além de `render`{#using-props-other-than-render}
239
242
240
-
It's important to remember that just because the pattern is called "render props" you don't *have to use a prop named `render`to use this pattern*. In fact, [*any* prop that is a function that a component uses to know what to render is technically a "render prop"](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce).
243
+
É importante lembrar que mesmo o nome padrão sendo _"render props"_, não quer dizer que você deve ter uma _prop_ chamada `render`para usar esse padrão. Na verdade, [*qualquer*_prop_ que é uma função usada por um componente para determinar o que renderizar é uma _"render prop"_](https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce).
241
244
242
-
Although the examples above use `render`, we could just as easily use the `children` prop!
245
+
Embora os exemplos acima usem a palavra `render`, poderíamos usar a _prop_`children`!
243
246
244
247
```js
245
248
<Mouse children={mouse=> (
246
249
<p>The mouse position is {mouse.x}, {mouse.y}</p>
247
250
)}/>
248
251
```
249
252
250
-
And remember, the `children`prop doesn't actually need to be named in the list of "attributes" in your JSX element. Instead, you can put it directly *inside* the element!
253
+
Lembre-se, a _prop_`children`não precisar estar nomeada na lista de "atributos" do seu elemento JSX. Ao invés disso, você pode inserí-la _dentro_ do seu elemento!
251
254
252
255
```js
253
256
<Mouse>
@@ -257,27 +260,28 @@ And remember, the `children` prop doesn't actually need to be named in the list
257
260
</Mouse>
258
261
```
259
262
260
-
You'll see this technique used in the [react-motion](https://github.com/chenglou/react-motion) API.
263
+
Você pode ver essa técnica sendo usada na API [react-motion](https://github.com/chenglou/react-motion).
261
264
262
-
Since this technique is a little unusual, you'll probably want to explicitly state that `children` should be a function in your `propTypes` when designing an API like this.
265
+
266
+
Dado que essa é uma técnica um pouco incomum, quando você estiver criando uma API como essa, você provavelmente vai querer definir nos seus `propTypes` que `children` deve ser uma função.
263
267
264
268
```js
265
269
Mouse.propTypes= {
266
270
children:PropTypes.func.isRequired
267
271
};
268
272
```
269
273
270
-
## Caveats {#caveats}
274
+
## Avisos {#caveats}
271
275
272
-
### Be careful when using Render Props with React.PureComponent {#be-careful-when-using-render-props-with-reactpurecomponent}
276
+
### Tenha cuidado ao utilizar _Render Props_ num React.PureComponent {#be-careful-when-using-render-props-with-reactpurecomponent}
273
277
274
-
Using a render prop can negate the advantage that comes from using [`React.PureComponent`](/docs/react-api.html#reactpurecomponent)if you create the function inside a `render` method. This is because the shallow prop comparison will always return`false`for new props, and each `render`in this case will generate a new value for the render prop.
278
+
Usar uma _render prop_ pode anular a vantagem de utilizar [`React.PureComponent`](/docs/react-api.html#reactpurecomponent)se você criar uma função dentro de um método `render`. Isso se deve à comparação superficial de _prop_ sempre retornar`false`para novas _props_, e, nesse caso, cada `render`vai gerar um novo valor para a _render prop_.
275
279
276
-
For example, continuing with our `<Mouse>`component from above, if`Mouse`were to extend `React.PureComponent`instead of `React.Component`, our example would look like this:
280
+
Por exemplo, continuando com o componente `<Mouse>`acima, se`Mouse`estendesse `React.PureComponent`no lugar de `React.Component`, nosso exemplo seria assim:
277
281
278
282
```js
279
283
classMouseextendsReact.PureComponent {
280
-
//Same implementation as above...
284
+
//Mesma implementação de antes...
281
285
}
282
286
283
287
classMouseTrackerextendsReact.Component {
@@ -287,8 +291,8 @@ class MouseTracker extends React.Component {
287
291
<h1>Move the mouse around!</h1>
288
292
289
293
{/*
290
-
This is bad! The value of the `render` prop will
291
-
be different on each render.
294
+
Isso é ruim! O valor da prop `render` vai ser
295
+
diferente para cara render.
292
296
*/}
293
297
<Mouse render={mouse=> (
294
298
<Cat mouse={mouse} />
@@ -299,14 +303,15 @@ class MouseTracker extends React.Component {
299
303
}
300
304
```
301
305
302
-
In this example, each time `<MouseTracker>`renders, it generates a new function as the value of the `<Mouse render>` prop, thus negating the effect of`<Mouse>`extending`React.PureComponent` in the first place!
306
+
Nesse exemplo, cada vez que `<MouseTracker>`renderiza, ele gera uma nova função como valor da prop `<Mouse render>`, anulando assim o efeito de`<Mouse>`estender`React.PureComponent`!
303
307
304
-
To get around this problem, you can sometimes define the prop as an instance method, like so:
308
+
Para contornar esse problema, você pode definir a prop como um método de instância:
305
309
306
310
```js
307
311
classMouseTrackerextendsReact.Component {
308
-
// Defined as an instance method, `this.renderTheCat` always
309
-
// refers to *same* function when we use it in render
312
+
// Definindo como um método de instância, `this.renderTheCat`
313
+
// sempre se refere a *mesma* função quando chamamos na
314
+
// renderização
310
315
renderTheCat(mouse) {
311
316
return<Cat mouse={mouse} />;
312
317
}
@@ -322,4 +327,4 @@ class MouseTracker extends React.Component {
322
327
}
323
328
```
324
329
325
-
In cases where you cannot define the prop statically (e.g. because you need to close over the component's props and/or state)`<Mouse>`should extend`React.Component` instead.
330
+
Nos casos onde você não pode definir a prop estaticamente (por exemplo, quando você precisa esconder as props e o estado do componente),`<Mouse>`deveria estender`React.Component`.
0 commit comments