Skip to content

Context page: Italian Translation based on issue #60 #259

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

Closed
wants to merge 24 commits into from
Closed
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 70 additions & 59 deletions content/docs/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,44 @@ title: Context
permalink: docs/context.html
---

Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Context fornisce un modo per passare i dati attraverso l'albero dei componenti senza dover passare manualmente i props ad ogni livello.

In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
In una tipica applicazione React, i dati sono passati dall'alto verso basso (da genitore a figlio) tramite i props, ma questo può essere
complicato per certi tipi di props (ad esempio una preferenza locale, il cambio di tema dell'interfaccia utente) che sono richiesti da molti componenti all'interno di un'applicazione. Context fornisce un modo per condividere valori come questi attraverso i diversi componenti senza dover passare esplicitamente una prop attraverso ogni livello dell'albero.

- [When to Use Context](#when-to-use-context)
- [Before You Use Context](#before-you-use-context)

- [Quando usare il Context](#when-to-use-context)
- [Prima di usare il Context](#before-you-use-context)
- [API](#api)
- [React.createContext](#reactcreatecontext)
- [Context.Provider](#contextprovider)
- [Class.contextType](#classcontexttype)
- [Context.Consumer](#contextconsumer)
- [Context.displayName](#contextdisplayname)
- [Examples](#examples)
- [Dynamic Context](#dynamic-context)
- [Updating Context from a Nested Component](#updating-context-from-a-nested-component)
- [Consuming Multiple Contexts](#consuming-multiple-contexts)
- [Caveats](#caveats)
- [Legacy API](#legacy-api)
- [Esempi](#examples)
- [Context dinamico](#dynamic-context)
- [Aggiornare il Context da un Componente Annidato](#updating-context-from-a-nested-component)
- [Consumare più Context](#consuming-multiple-contexts)
- [Avvertenze](#caveats)
- [API Legacy](#legacy-api)

## When to Use Context {#when-to-use-context}
## Quando usare il Context {#when-to-use-context}

Context is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a "theme" prop in order to style the Button component:
Context é progettato per condividire i dati che possono essere considerati "globali" per un albero di componenti React, come l'attuale utente autenticato, tema, o lingua preferita. Ad esempio, nel codice seguente passiamo manualmente attraverso un prop "theme" per dare style al componente Button:

`embed:context/motivation-problem.js`

Using context, we can avoid passing props through intermediate elements:
Usando il Context, possiamo evitare di passare i props attraverso elementi intermedi:

`embed:context/motivation-solution.js`

## Before You Use Context {#before-you-use-context}
## Prima di utilizzare il Context {#before-you-use-context}

Context is primarily used when some data needs to be accessible by *many* components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.
Context è principalmente utilizzato quando alcuni dati devono essere accessibili da *molti* componenti ai diversi livelli di nidificazione. Dovrebbe essere applicato con moderazione in quanto rende più difficile il riutilizzo dei componenti.

**If you only want to avoid passing some props through many levels, [component composition](/docs/composition-vs-inheritance.html) is often a simpler solution than context.**
**Se vuoi solo evitare di passare alcuni prop attraverso molti livelli, [composizione del componente](/docs/composition-vs-inheritance.html) è spesso una soluzione più semplice rispetto context.**

For example, consider a `Page` component that passes a `user` and `avatarSize` prop several levels down so that deeply nested `Link` and `Avatar` components can read it:
Per esempio, considera un componente `Page` che passa i props `user` e `avatarSize` diversi livelli verso il basso affichè i componenti `Link` e `Avatar` profondamente annidati lo possano leggere:

```js
<Page user={user} avatarSize={avatarSize} />
Expand All @@ -53,9 +55,9 @@ For example, consider a `Page` component that passes a `user` and `avatarSize` p
</Link>
```

It might feel redundant to pass down the `user` and `avatarSize` props through many levels if in the end only the `Avatar` component really needs it. It's also annoying that whenever the `Avatar` component needs more props from the top, you have to add them at all the intermediate levels too.
Potrebbe sembrare ridondante passare i props `user` e `avatarSize` attraverso molti livelli se alla fine solo il componente `Avatar` ne ha davvero bisogno. È anche fastidioso che ogni volta che il componente `Avatar` ha bisogno di più props dall'alto, devi aggiungerli anche a tutti i livelli intermedi.

One way to solve this issue **without context** is to [pass down the `Avatar` component itself](/docs/composition-vs-inheritance.html#containment) so that the intermediate components don't need to know about the `user` or `avatarSize` props:
Un modo per risolvere questo problema **senza il context** è di [passare giù il componente `Avatar` stesso](/docs/composition-vs-inheritance.html#containment) in modo che i componenti intermedi non debbano conoscere i props `user` o `avatarSize`:

```js
function Page(props) {
Expand All @@ -78,11 +80,13 @@ function Page(props) {
{props.userLink}
```

With this change, only the top-most Page component needs to know about the `Link` and `Avatar` components' use of `user` and `avatarSize`.
Con questo cambiamento, solo il componente Page più in alto deve conoscere l'utilizzo di `user` e `avatarSize` da componenti `Link` e `Avatar`.

Questa *inversione del controllo* può rendere il tuo codice più pulito in molti casi riducendo il numero di props che hai bisgno di passare attraverso la tua applicazione e fornendo un maggiore controllo ai componenti radice.

This *inversion of control* can make your code cleaner in many cases by reducing the amount of props you need to pass through your application and giving more control to the root components. However, this isn't the right choice in every case: moving more complexity higher in the tree makes those higher-level components more complicated and forces the lower-level components to be more flexible than you may want.
Tuttavia, questa non è la scelta giusta in ogni caso: spostare più complessità nell'albero verso l'alto rende più complicati i componenti di alto livello e costringe i componenti di basso livello a essere più flessibili di quanto vorresti.

You're not limited to a single child for a component. You may pass multiple children, or even have multiple separate "slots" for children, [as documented here](/docs/composition-vs-inheritance.html#containment):
Non sei limitato a un singolo figlio per un componente. Potresti passare figli multipli, o anche avere più "slot" separati per i figli, [come documentato qui](/docs/composition-vs-inheritance.html#containment):

```js
function Page(props) {
Expand All @@ -103,10 +107,14 @@ function Page(props) {
);
}
```
Questo modello è sufficiente per molti casi in cui è necessario disaccoppiare un figlio dai suoi genitori immediati.

Lo puoi portare ancora avanti con [render props](/docs/render-props.html) se il figlio ha bisogno di comunicare con il genitore prima di renderizzare.

This pattern is sufficient for many cases when you need to decouple a child from its immediate parents. You can take it even further with [render props](/docs/render-props.html) if the child needs to communicate with the parent before rendering.
Tuttavia, alcune volte i stessi dati devono essere accessbili da molti componenti nell'albero, ed ai diversi livelli di nidificazione.
Il context permette di "trasmettere" tale dati, e le modifiche ad essi , a tutte i componenti di seguito.

However, sometimes the same data needs to be accessible by many components in the tree, and at different nesting levels. Context lets you "broadcast" such data, and changes to it, to all components below. Common examples where using context might be simpler than the alternatives include managing the current locale, theme, or a data cache.
Esempi comuni dove context potrebbe essere più semplice delle alternative includono la gestione del locale corrente, del tema, o di una cache dei dati.

## API {#api}

Expand All @@ -116,27 +124,28 @@ However, sometimes the same data needs to be accessible by many components in th
const MyContext = React.createContext(defaultValue);
```

Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching `Provider` above it in the tree.
Crea un oggetto Context. Quando React renderizza un componente che si iscrive a questo oggetto Context, esso leggerà il valore context corrente dal `Provider` corrispondente più vicino sopra di esso nell'albero.

The `defaultValue` argument is **only** used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them. Note: passing `undefined` as a Provider value does not cause consuming components to use `defaultValue`.
L'argomento `defaultValue` è utilizzato **soltanto** quando un componente non ha un Provider corrispondente sopra di esso nell'albero.
Questo può essere utile per testare i componenti in isolamento senza avvolgerli. Nota: passando `undefined` come valore del Provider non causa ai componenti consumer di utilizzare `defaultValue`

### `Context.Provider` {#contextprovider}

```js
<MyContext.Provider value={/* some value */}>
```

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.
Ogni oggetto Context viene con un componente React Provider che consente ai componenti consumer di iscriversi alle modifiche del context.

The Provider component accepts a `value` prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
Il componente Provider accetta un props `value` da passare ai componenti consumer che sono discendenti di questo Provider. Un Provider può essere connesso a consumer multipli. I Provider possono essere nidificati per sovrascrivere i valori più profondi all'interno dell'albero.

All consumers that are descendants of a Provider will re-render whenever the Provider's `value` prop changes. The propagation from Provider to its descendant consumers (including [`.contextType`](#classcontexttype) and [`useContext`](/docs/hooks-reference.html#usecontext)) is not subject to the `shouldComponentUpdate` method, so the consumer is updated even when an ancestor component skips an update.
Tutti i consumer che sono discendenti di uno Provider si ri-renderizzeranno ogni volta il props `value` dello Provider cambia. La propagazione dallo Provider fino ai suoi consumer discendenti (includendo [`.contextType`](#classcontexttype) e [`useContext`](/docs/hooks-reference.html#usecontext)) non sono soggetti al metodo `shouldComponentUpdate`, quindi il consumer è aggiornato anche quando un componente antenato salta un aggiornamento.

Changes are determined by comparing the new and old values using the same algorithm as [`Object.is`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description).
Le modifiche sono determinate confrontando nuovi e vecchi valori usand lo stesso algoritmo di [`Object.is`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description).

> Note
> Nota
>
> The way changes are determined can cause some issues when passing objects as `value`: see [Caveats](#caveats).
> Il modo in cui vengono determinate le modifiche può causare alcuni problemi quando si passano oggetti come "valore": vedere [Avvertenze](#caveats).

### `Class.contextType` {#classcontexttype}

Expand All @@ -162,14 +171,15 @@ class MyClass extends React.Component {
MyClass.contextType = MyContext;
```

The `contextType` property on a class can be assigned a Context object created by [`React.createContext()`](#reactcreatecontext). This lets you consume the nearest current value of that Context type using `this.context`. You can reference this in any of the lifecycle methods including the render function.
La proprietà `contextType` in una classe può essere assegnata ad un oggetto Context creato da [`React.createContext()`](#reactcreatecontext).
Ciò consente di consumare il valore corrente più vicino di quel tipo di Context usando `this.context`.
È possibile fare riferimento a questo in uno qualsiasi dei metodi lifecycle, inclusa la funzione render.

> Note:
> Nota:
>
> You can only subscribe to a single context using this API. If you need to read more than one see [Consuming Multiple Contexts](#consuming-multiple-contexts).
> Puoi iscriverti solo ad un singolo context utilizzando questa API. Se hai bisogno di leggere più di uno vedi [Consumo di Più Context](#consuming-multiple-contexts).
>
> If you are using the experimental [public class fields syntax](https://babeljs.io/docs/plugins/transform-class-properties/), you can use a **static** class field to initialize your `contextType`.

> Se si utilizza la [sintassi dei campi di classe pubblica](https://babeljs.io/docs/plugins/transform-class-properties/) sperimentale, puoi usare un campo di classe **statico** per inizializzare il tuo `contextType`

```js
class MyClass extends React.Component {
Expand All @@ -185,23 +195,23 @@ class MyClass extends React.Component {

```js
<MyContext.Consumer>
{value => /* render something based on the context value */}
{value => /* render something based on the context value */}
</MyContext.Consumer>
```

A React component that subscribes to context changes. This lets you subscribe to a context within a [function component](/docs/components-and-props.html#function-and-class-components).
Un componente React che si iscrive alle modifiche. Ciò consente di iscriverti ad un context dentro un [componente funzione](/docs/components-and-props.html#function-and-class-components).

Requires a [function as a child](/docs/render-props.html#using-props-other-than-render). The function receives the current context value and returns a React node. The `value` argument passed to the function will be equal to the `value` prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the `value` argument will be equal to the `defaultValue` that was passed to `createContext()`.
Richiede una [funzione come un figlio](/docs/render-props.html#using-props-other-than-render). La funzione riceve il valore del context corrente e restituisce un nodo React. L'argomento `value` passato alla funzione sarà uguale al prop `value` del Provider per questo context sopra nell'albero. Se non c'è un Provider per questo context sopra, l'argomento `value` sarà uguale a `defaultValue` che era stato passato a `createContext()`.

> Note
> Nota
>
> For more information about the 'function as a child' pattern, see [render props](/docs/render-props.html).
> Per ulteriori informazioni sul modello 'funzione come figlio', vedere [render props](/docs/render-props.html).

### `Context.displayName` {#contextdisplayname}

Context object accepts a `displayName` string property. React DevTools uses this string to determine what to display for the context.
L'oggetto Context accetta una proprietà stringa `displayName`. I React DevTools utilizzano questa stringa per determinare cosa visualizzare per il context.

For example, the following component will appear as MyDisplayName in the DevTools:
Per esempio, il seguente componente apparirà come MyDisplayName nei DevTools:

```js{2}
const MyContext = React.createContext(/* some value */);
Expand All @@ -211,11 +221,11 @@ MyContext.displayName = 'MyDisplayName';
<MyContext.Consumer> // "MyDisplayName.Consumer" in DevTools
```

## Examples {#examples}
## Esempi {#examples}

### Dynamic Context {#dynamic-context}
### Context Dinamico {#dynamic-context}

A more complex example with dynamic values for the theme:
Un esempio più complesso con valori dinamici per il tema:

**theme-context.js**
`embed:context/theme-detailed-theme-context.js`
Expand All @@ -226,9 +236,9 @@ A more complex example with dynamic values for the theme:
**app.js**
`embed:context/theme-detailed-app.js`

### Updating Context from a Nested Component {#updating-context-from-a-nested-component}
### Aggiornamento del Context da un Componente Nidificato {#updating-context-from-a-nested-component}

It is often necessary to update the context from a component that is nested somewhere deeply in the component tree. In this case you can pass a function down through the context to allow consumers to update the context:
Spesso è necessario aggiornare il context da un componente che è nidificato profondamente da qualche parte nell'albero dei componenti. In questo caso è possibile passare una funzione attraverso il context per consentire ai consumer di aggiornare il context:

**theme-context.js**
`embed:context/updating-nested-context-context.js`
Expand All @@ -239,28 +249,29 @@ It is often necessary to update the context from a component that is nested some
**app.js**
`embed:context/updating-nested-context-app.js`

### Consuming Multiple Contexts {#consuming-multiple-contexts}
### Consumo dei Context Multipli {#consuming-multiple-contexts}

To keep context re-rendering fast, React needs to make each context consumer a separate node in the tree.
Per mantenere veloce la ri-renderizzazione del context, React deve rendere ogni consumer del context un nodo separato nell'albero.

`embed:context/multiple-contexts.js`

If two or more context values are often used together, you might want to consider creating your own render prop component that provides both.
Se due o più valori del context sono spesso utilizzati insieme, si potrebbe prendere in considerazione la creazione di un proprio componente render props che fornisce entrambi.

## Avvertenze {#caveats}

## Caveats {#caveats}
Poiché il context utilizza l'identità di riferimento per determinare quando ri-renderizzare, ci sono alcuni trabocchetti che potrebbero innescare renderizzazioni non intenzionali nei consumer quando il genitore di uno provider si ri-renderizza.

Because context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider's parent re-renders. For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for `value`:
Per esempio, il codice sotto ri-renderizzerà tutti i consumer ogni volta che lo Provider si ri-renderizza perchè un nuovo oggetto è sempre creato per `value`:

`embed:context/reference-caveats-problem.js`


To get around this, lift the value into the parent's state:
Per aggirare questo problema, sollevare il valore nello state del genitore:

`embed:context/reference-caveats-solution.js`

## Legacy API {#legacy-api}
## API Legacy{#legacy-api}

> Note
> Nota
>
> React previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. The legacy API will be removed in a future major React version. Read the [legacy context docs here](/docs/legacy-context.html).

> React precedentemente fornito con un'API sperimentale del context. La vecchia API sarà supportata in tutte le 16.x versioni, ma le applicazioni che lo utilizzano dovrebbero migrare alla nuova versione. L'API Legacy verrà rimossa in una versione futura principale di React. Leggi i [docs del context legacy](/docs/legacy-context.html).