Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translation of blog post: "2018-05-23-react-v-16-4" #181

Merged
merged 13 commits into from Apr 18, 2019
Merged
91 changes: 46 additions & 45 deletions content/blog/2018-05-23-react-v-16-4.md
Expand Up @@ -3,13 +3,13 @@ title: "React v16.4.0: Pointer Events"
author: [acdlite]
---

The latest minor release adds support for an oft-requested feature: pointer events!
A última release minor adicionou suporte para um recurso solicitado frequentemente: eventos de ponteiros!

It also includes a bugfix for `getDerivedStateFromProps`. Check out the full [changelog](#changelog) below.
Também foi incluso uma correção de erro para o `getDerivedStateFromProps`. Confira o [changelog](#changelog) completo abaixo.

## Pointer Events {#pointer-events}
## Eventos de Ponteiros {#pointer-events}

The following event types are now available in React DOM:
Os tipos de eventos seguintes estão disponíveis agora no React DOM:

- `onPointerDown`
- `onPointerMove`
Expand All @@ -22,86 +22,87 @@ The following event types are now available in React DOM:
- `onPointerOver`
- `onPointerOut`

Please note that these events will only work in browsers that support the [Pointer Events](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) specification. (At the time of this writing, this includes the latest versions of Chrome, Firefox, Edge, and Internet Explorer.) If your application depends on pointer events, we recommend using a third-party pointer events polyfill. We have opted not to include such a polyfill in React DOM, to avoid an increase in bundle size.
Tenha em mente que estes eventos só funcionarão em navegadores que suportam a especificação de [eventos de ponteiros](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events). (No momento da redação deste texto, estão inclusas as versões mais recentes do Chrome, Firefox, Edge e Internet Explorer). Se a sua aplicação depende de eventos de ponteiros, recomendamos a utilização de um polyfill desenvolvido por terceiros. Optamos por não incluir tal polyfill no React DOM, para evitar o aumento de tamanho do pacote.

[Check out this example on CodeSandbox.](codesandbox://16-4-release-blog-post/pointer-events-example)
[Confira este exemplo em CodeSandbox.](codesandbox://16-4-release-blog-post/pointer-events-example)

Huge thanks to [Philipp Spiess](https://github.com/philipp-spiess) for contributing this change!
Enormes agradecimentos a [Philipp Spiess](https://github.com/philipp-spiess) por contribuir com esta mudança!

## Bugfix for `getDerivedStateFromProps` {#bugfix-for-getderivedstatefromprops}
## Correção de erro para o `getDerivedStateFromProps` {#bugfix-for-getderivedstatefromprops}
rn4n marked this conversation as resolved.
Show resolved Hide resolved

`getDerivedStateFromProps` is now called every time a component is rendered, regardless of the cause of the update. Previously, it was only called if the component was re-rendered by its parent, and would not fire as the result of a local `setState`. This was an oversight in the initial implementation that has now been corrected. The previous behavior was more similar to `componentWillReceiveProps`, but the improved behavior ensures compatibility with React's upcoming asynchronous rendering mode.
`getDerivedStateFromProps` agora é chamado toda vez que um componente é renderizado, independentemente da causa da atualização. Anteriormente, isto era chamado se componente foi re-renderizado por seu pai, e não dispararia como resultado de um `setState` local. Este foi um descuido na implementação inicial que agora foi corrigido. O comportamento anterior era mais semelhante ao `componentWillReceiveProps`, mas o comportamento melhorado garante compatibilidade com o próximo modo de renderização assíncrono do React.

**This bug fix will not affect most apps**, but it may cause issues with a small fraction of components. The rare cases where it does matter fall into one of two categories:
**Esta correção de erro não afeta a maioria das aplicações**, mas pode causar problemas com uma pequena fração de componentes. Os raros casos que importam se enquadram em uma das duas categorias:

### 1. Avoid Side Effects in `getDerivedStateFromProps` {#1-avoid-side-effects-in-getderivedstatefromprops}
### 1. Evite efeitos colaterais em `getDerivedStateFromProps` {#1-avoid-side-effects-in-getderivedstatefromprops}
rn4n marked this conversation as resolved.
Show resolved Hide resolved

Like the render method, `getDerivedStateFromProps` should be a pure function of props and state. Side effects in `getDerivedStateFromProps` were never supported, but since it now fires more often than it used to, the recent change may expose previously undiscovered bugs.
Assim como o método render, `getDerivedStateFromProps` deve ser uma função pura de props e state. Efeitos colaterais em `getDerivedStateFromProps` nunca foram suportados, mas uma vez que agora é disparado com maior frequência do que costumava, a alteração recente pode expor erros não descobertos anteriormente.

Side effectful code should be moved to other methods: for example, Flux dispatches typically belong inside the originating event handler, and manual DOM mutations belong inside componentDidMount or componentDidUpdate. You can read more about this in our recent post about [preparing for asynchronous rendering](/blog/2018/03/27/update-on-async-rendering.html).
Código com efeito colateral deve ser movido para outros métodos: por exemplo, os despachos do Flux normalmente pertencem dentro do manipulador de eventos de origem, e as mutações manuais do DOM pertencem dentro de componentDidMount ou componentDidUpdate. Você pode ler mais sobre isso em nosso post recente sobre [preparando para renderização assíncrona](/blog/2018/03/27/update-on-async-rendering.html).

### 2. Compare Incoming Props to Previous Props When Computing Controlled Values {#2-compare-incoming-props-to-previous-props-when-computing-controlled-values}
### 2. Comparar propriedades recebidas com propriedades anteriores ao computar valores controlados {#2-compare-incoming-props-to-previous-props-when-computing-controlled-values}
jhonmike marked this conversation as resolved.
Show resolved Hide resolved

The following code assumes `getDerivedStateFromProps` only fires on prop changes:
O código a seguir assume que `getDerivedStateFromProps` será executado somente em alterações de props:

```js
static getDerivedStateFromProps(props, state) {
if (props.value !== state.controlledValue) {
return {
// Since this method fires on both props and state changes, local updates
// to the controlled value will be ignored, because the props version
// always overrides it. Oops!
// Uma vez que este métodoé executado em ambas as alterações de props e state,
rn4n marked this conversation as resolved.
Show resolved Hide resolved
// updates locais no valor controlado serão ignorados, porque a versão de props
// sempre sobrescreve isto. Oops!
controlledValue: props.value,
};
}
return null;
}
```

One possible way to fix this is to compare the incoming value to the previous value by storing the previous props in state:
Uma maneira possível de corrigir isto é comparando o valor de recebido com o valor anterior por armazenar as props anteriores no estado:

```js
static getDerivedStateFromProps(props, state) {
const prevProps = state.prevProps || {};
// Compare the incoming prop to previous prop
// Comparando a prop recebida com a prop anterior
const controlledValue =
prevProps.value !== props.value
? props.value
: state.controlledValue;
return {
// Store the previous props in state
// Armazena a prop anterior no state
prevProps: props,
controlledValue,
};
}
```

However, **code that "mirrors" props in state usually contains bugs**, whether you use the newer `getDerivedStateFromProps` or the legacy `componentWillReceiveProps`. We published a follow-up blog post that explains these problems in more detail, and suggests [simpler solutions that don't involve `getDerivedStateFromProps()`](/blog/2018/06/07/you-probably-dont-need-derived-state.html).
No entanto, **código que "espelha" props no estado geralmente contém bugs**, se você utiliza a mais recente `getDerivedStateFromProps` ou a legada `componentWillReceiveProps`. Publicamos uma postagem no blog que explica esses problemas com mais detalhes e sugere [soluções mais simples que não envolvem `getDerivedStateFromProps()`](/blog/2018/06/07/you-probably-dont-need-derived-state.html).


## Installation {#installation}

React v16.4.0 is available on the npm registry.
React v16.4.0 está disponível no registro npm.

To install React 16 with Yarn, run:
Para instalar o React 16 com Yarn, execute:

```bash
yarn add react@^16.4.0 react-dom@^16.4.0
```

To install React 16 with npm, run:
Para instalar o React 16 com npm, execute:

```bash
npm install --save react@^16.4.0 react-dom@^16.4.0
```

We also provide UMD builds of React via a CDN:
Também fornecemos compilações UMD do React através de um CDN:

```html
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
```

Refer to the documentation for [detailed installation instructions](/docs/installation.html).
Consulte a documentação para obter [instruções de instalação detalhadas](/docs/installation.html).

## Changelog {#changelog}

Expand All @@ -111,33 +112,33 @@ Refer to the documentation for [detailed installation instructions](/docs/instal

### React DOM {#react-dom}

* Add support for the Pointer Events specification. ([@philipp-spiess](https://github.com/philipp-spiess) in [#12507](https://github.com/facebook/react/pull/12507))
* Properly call `getDerivedStateFromProps()` regardless of the reason for re-rendering. ([@acdlite](https://github.com/acdlite) in [#12600](https://github.com/facebook/react/pull/12600) and [#12802](https://github.com/facebook/react/pull/12802))
* Fix a bug that prevented context propagation in some cases. ([@gaearon](https://github.com/gaearon) in [#12708](https://github.com/facebook/react/pull/12708))
* Fix re-rendering of components using `forwardRef()` on a deeper `setState()`. ([@gaearon](https://github.com/gaearon) in [#12690](https://github.com/facebook/react/pull/12690))
* Fix some attributes incorrectly getting removed from custom element nodes. ([@airamrguez](https://github.com/airamrguez) in [#12702](https://github.com/facebook/react/pull/12702))
* Fix context providers to not bail out on children if there's a legacy context provider above. ([@gaearon](https://github.com/gaearon) in [#12586](https://github.com/facebook/react/pull/12586))
* Add the ability to specify `propTypes` on a context provider component. ([@nicolevy](https://github.com/nicolevy) in [#12658](https://github.com/facebook/react/pull/12658))
* Fix a false positive warning when using `react-lifecycles-compat` in `<StrictMode>`. ([@bvaughn](https://github.com/bvaughn) in [#12644](https://github.com/facebook/react/pull/12644))
* Warn when the `forwardRef()` render function has `propTypes` or `defaultProps`. ([@bvaughn](https://github.com/bvaughn) in [#12644](https://github.com/facebook/react/pull/12644))
* Improve how `forwardRef()` and context consumers are displayed in the component stack. ([@sophiebits](https://github.com/sophiebits) in [#12777](https://github.com/facebook/react/pull/12777))
* Change internal event names. This can break third-party packages that rely on React internals in unsupported ways. ([@philipp-spiess](https://github.com/philipp-spiess) in [#12629](https://github.com/facebook/react/pull/12629))
* Adicionando suporte a especificação de eventos de ponteiros. ([@philipp-spiess](https://github.com/philipp-spiess) em [#12507](https://github.com/facebook/react/pull/12507))
* Chamando `getDerivedStateFromProps()` corretamente independente do motivo de re-renderização. ([@acdlite](https://github.com/acdlite) em [#12600](https://github.com/facebook/react/pull/12600) and [#12802](https://github.com/facebook/react/pull/12802))
rn4n marked this conversation as resolved.
Show resolved Hide resolved
* Correção de erro que impediu a propagação de contexto em alguns casos. ([@gaearon](https://github.com/gaearon) em [#12708](https://github.com/facebook/react/pull/12708))
* Correção da re-renderização de componentes utilizando `forwardRef()` em um `setState()` mais profundo. ([@gaearon](https://github.com/gaearon) em [#12690](https://github.com/facebook/react/pull/12690))
* Corrigindo alguns atributos sendo removidos incorretamente de nós de elemento personalizado. ([@airamrguez](https://github.com/airamrguez) em [#12702](https://github.com/facebook/react/pull/12702))
* Corrigindo provedores de contexto para não salvar os filhos se há um provedor de contexto herdado acima. ([@gaearon](https://github.com/gaearon) em [#12586](https://github.com/facebook/react/pull/12586))
* Adicionando a capacidade de especificar `propTypes` em um componente de provedor de contexto. ([@nicolevy](https://github.com/nicolevy) em [#12658](https://github.com/facebook/react/pull/12658))
* Corrigindo um aviso de falso positivo ao usar `react-lifecycles-compat` em `<StrictMode>`. ([@bvaughn](https://github.com/bvaughn) em [#12644](https://github.com/facebook/react/pull/12644))
* Aviso quando a função de renderização `forwardRef()` tiver `propTypes` ou `defaultProps`. ([@bvaughn](https://github.com/bvaughn) em [#12644](https://github.com/facebook/react/pull/12644))
* Melhorar como `forwardRef()` e os consumidores de contexto são exibidos na pilha de componentes. ([@sophiebits](https://github.com/sophiebits) em [#12777](https://github.com/facebook/react/pull/12777))
* Alterando nomes de eventos internos. Isso pode quebrar pacotes de terceiros que dependem dos internos do React de maneiras sem suporte. ([@philipp-spiess](https://github.com/philipp-spiess) in [#12629](https://github.com/facebook/react/pull/12629))
rn4n marked this conversation as resolved.
Show resolved Hide resolved

### React Test Renderer {#react-test-renderer}

* Fix the `getDerivedStateFromProps()` support to match the new React DOM behavior. ([@koba04](https://github.com/koba04) in [#12676](https://github.com/facebook/react/pull/12676))
* Fix a `testInstance.parent` crash when the parent is a fragment or another special node. ([@gaearon](https://github.com/gaearon) in [#12813](https://github.com/facebook/react/pull/12813))
* `forwardRef()` components are now discoverable by the test renderer traversal methods. ([@gaearon](https://github.com/gaearon) in [#12725](https://github.com/facebook/react/pull/12725))
* Shallow renderer now ignores `setState()` updaters that return `null` or `undefined`. ([@koba04](https://github.com/koba04) in [#12756](https://github.com/facebook/react/pull/12756))
* Corrigindo o suporte de `getDerivedStateFromProps()` para corresponder ao novo comportamento do React DOM. ([@koba04](https://github.com/koba04) em [#12676](https://github.com/facebook/react/pull/12676))
* Corrigir uma falha de `testInstance.parent` quando o pai é um fragmento ou outro nó especial. ([@gaearon](https://github.com/gaearon) em [#12813](https://github.com/facebook/react/pull/12813))
* Componentes `forwardRef()` agora são detectáveis pelos métodos do renderizador traversal de teste. ([@gaearon](https://github.com/gaearon) em [#12725](https://github.com/facebook/react/pull/12725))
* O ReactShallowRenderer agora ignora os atualizadores de `setState()` que retornam `null` ou `undefined`. ([@koba04](https://github.com/koba04) em [#12756](https://github.com/facebook/react/pull/12756))

### React ART {#react-art}

* Fix reading context provided from the tree managed by React DOM. ([@acdlite](https://github.com/acdlite) in [#12779](https://github.com/facebook/react/pull/12779))
* Corrigiingo o contexto de leitura fornecido a partir da árvore gerenciada pelo React DOM. ([@acdlite](https://github.com/acdlite) em [#12779](https://github.com/facebook/react/pull/12779))

### React Call Return (Experimental) {#react-call-return-experimental}

* This experiment was deleted because it was affecting the bundle size and the API wasn't good enough. It's likely to come back in the future in some other form. ([@gaearon](https://github.com/gaearon) in [#12820](https://github.com/facebook/react/pull/12820))
* Este experimento foi excluído porque estava afetando o tamanho do pacote e a API não era suficientemente boa. É provável que volte no futuro de alguma outra forma. ([@gaearon](https://github.com/gaearon) em [#12820](https://github.com/facebook/react/pull/12820))

### React Reconciler (Experimental) {#react-reconciler-experimental}

* The [new host config shape](https://github.com/facebook/react/blob/c601f7a64640290af85c9f0e33c78480656b46bc/packages/react-noop-renderer/src/createReactNoop.js#L82-L285) is flat and doesn't use nested objects. ([@gaearon](https://github.com/gaearon) in [#12792](https://github.com/facebook/react/pull/12792))
* A [nova forma de configuração do host](https://github.com/facebook/react/blob/c601f7a64640290af85c9f0e33c78480656b46bc/packages/react-noop-renderer/src/createReactNoop.js#L82-L285) é plana e não usa objetos aninhados. ([@gaearon](https://github.com/gaearon) em [#12792](https://github.com/facebook/react/pull/12792))