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
`createContext`returns a <CodeStepstep={1}>context object</CodeStep>. Components can read context by passing it to[`useContext()`](/apis/react/useContext):
34
+
`createContext`retorna un <CodeStepstep={1}>objeto context</CodeStep>. Los componentes pueden leer el contexto pasándolo a[`useContext()`](/apis/react/useContext):
By default, the values they receive will be the <CodeStepstep={3}>default values</CodeStep> you have specified when creating the contexts. However, by itself this isn't useful because the default values never change.
48
+
De forma predeterminada, los valores que reciben serán los <CodeStepstep={3}>valores predeterminados</CodeStep> que se han especificado al crear los contextos. Sin embargo, esto por sí mismo no es útil porque los valores predeterminados nunca cambian.
49
49
50
-
Context is useful because you can**provide other, dynamic values from your components:**
50
+
El contexto es útil porque puede**proporcionar otros valores dinámicos a sus componentes:**
51
51
52
52
```js {8-9,11-12}
53
53
functionApp() {
@@ -66,15 +66,15 @@ function App() {
66
66
}
67
67
```
68
68
69
-
Now the `Page`component and any components inside it, no matter how deep, will "see" the passed context values. If the passed context values change, React will re-render the components reading the context as well.
69
+
Ahora el componente `Page`y cualquier componente dentro de él, sin importar cuán profundo sea, "verán" los valores de contexto dados. Si los valores del contexto dados cambian, React volverá a renderizar los componentes leyendo el contexto también.
70
70
71
-
[Read more about reading and providing context and see examples.](/apis/react/useContext)
71
+
[Aprende más sobre leer y proporcionar un contexto, y consulta ejemplos.](/apis/react/useContext)
72
72
73
73
---
74
74
75
-
### Importing and exporting context from a file {/*importing-and-exporting-context-from-a-file*/}
75
+
### Importación y exportación de contexto desde un archivo {/*importing-and-exporting-context-from-a-file*/}
76
76
77
-
Often, components in different files will need access to the same context. This is why it's common to declare contexts in a separate file. Then you can use the[`export` statement](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export)to make context available for other files:
77
+
A menudo, los componentes de diferentes archivos necesitarán acceso al mismo contexto. Por eso es común declarar contextos en un archivo separado. Luego puedes usar la declaración[`export`](https://developer.mozilla.org/es/docs/web/javascript/reference/statements/export)para hacer que el contexto esté disponible para otros archivos:
Components declared in other files can then use the [`import`](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import) statement to read or provide this context:
87
+
Los componentes declarados en otros archivos pueden usar la declaración [`import`](https://developer.mozilla.org/es/docs/web/javascript/reference/statements/import) para leer o proveer un contexto:
88
88
89
89
```js {2}
90
90
// Button.js
@@ -112,40 +112,40 @@ function App() {
112
112
}
113
113
```
114
114
115
-
This works similar to [importing and exporting components.](/learn/importing-and-exporting-components)
115
+
Esto funciona de manera similar a la [importación y exportación de componentes.](/learn/importing-and-exporting-components)
Call `createContext`outside of any components to create a context.
123
+
Puedes llamar a `createContext`fuera de cualquier componente para crear un contexto.
124
124
125
125
```js
126
126
import { createContext } from 'react';
127
127
128
128
const ThemeContext = createContext('light');
129
129
```
130
130
131
-
#### Parameters {/*parameters*/}
131
+
#### Parámetros {/*parameters*/}
132
132
133
-
*`defaultValue`:The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don't have any meaningful default value, specify `null`. The default value is meant as a "last resort" fallback. It is static and never changes over time.
133
+
*`defaultValue`:El valor que desees que tenga el contexto cuando no hay un proveedor de contexto coincidente en el árbol sobre el componente que lee el contexto. Si no tiene ningún valor predeterminado significativo, especifica`null`. El valor predeterminado se entiende como una reserva de "último recurso". Es estático y nunca cambia con el tiempo.
134
134
135
-
#### Returns {/*returns*/}
135
+
#### Retorna {/*returns*/}
136
136
137
-
`createContext` returns a context object.
137
+
`createContext`devuelve un objeto de contexto.
138
138
139
-
**The context object itself does not hold any information.** It represents _which_ context other components can read or provide. Typically, you will use [`SomeContext.Provider`](#provider) in components above to specify the context value, and call [`useContext(SomeContext)`](/apis/react/useContext) in components below to read it. The context object has a few properties:
139
+
**El objeto de contexto en sí no contiene ninguna información.**Representa _qué_ contexto pueden leer o proporcionar otros componentes. Por lo general, utilizará [`SomeContext.Provider`](#provider) en los componentes anteriores para especificar el valor de contexto y llamará a [`useContext(SomeContext)`](/apis/react/useContext) en los componentes siguientes para leerlo. El objeto de contexto tiene algunas propiedades:
140
140
141
-
* `SomeContext.Provider` lets you provide the context value to components.
142
-
* `SomeContext.Consumer` is an alternative and rarely used way to read the context value.
141
+
*`SomeContext.Provider`Te permite proporcionar el valor de contexto a los componentes.
142
+
*`SomeContext.Consumer`Es una forma alternativa y poco utilizada de leer el valor del contexto..
143
143
144
144
---
145
145
146
146
### `SomeContext.Provider` {/*provider*/}
147
147
148
-
Wrap your components into a context provider to specify the value of this context for all components inside:
148
+
Envuelve tus componentes en un proveedor de contexto para especificar el valor de este contexto para todos los componentes dentro:
149
149
150
150
```js
151
151
function App() {
@@ -161,17 +161,17 @@ function App() {
161
161
162
162
#### Props {/*provider-props*/}
163
163
164
-
* `value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](/apis/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it.
164
+
*`value`:El valor que desees pasar a todos los componentes que leen este contexto dentro de este proveedor, sin importar cuán profundo sea. El valor de contexto puede ser de cualquier tipo. Un componente que llama a [`useContext(SomeContext)`](/apis/react/useContext) dentro del proveedor recibe el valor (`value`) del proveedor de contexto correspondiente más interno que se encuentra arriba.
165
165
166
166
---
167
167
168
168
### `SomeContext.Consumer` {/*consumer*/}
169
169
170
-
Before `useContext` existed, there was an older way to read context:
170
+
Antes de que existiera `useContext`, había una forma más antigua de leer el contexto:
171
171
172
172
```js
173
173
function Button() {
174
-
// 🟡 Legacy way (not recommended)
174
+
// 🟡 Forma antigua (no recomendado)
175
175
return (
176
176
<ThemeContext.Consumer>
177
177
{theme => (
@@ -182,34 +182,34 @@ function Button() {
182
182
}
183
183
```
184
184
185
-
Although this older way still works, but **newly written code should read context with [`useContext()`](/apis/react/useContext) instead:**
185
+
Aunque esta forma aún funciona, **el código recién escrito debería leer el contexto con [`useContext()`](/apis/react/useContext) en su lugar:**
186
186
187
187
```js
188
188
function Button() {
189
-
// ✅ Recommended way
189
+
// ✅ Forma recomendada
190
190
const theme = useContext(ThemeContext);
191
191
return <button className={theme} />;
192
192
}
193
193
```
194
194
195
195
#### Props {/*consumer-props*/}
196
196
197
-
* `children`: A function. React will call the function you pass with the current context value determined by the same algorithm as [`useContext()`](/apis/react/useContext) does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context passed from the parent components have changed.
197
+
*`children`:Una función. Reactllamará a la función que pases con el valor de contexto actual determinado por el mismo algoritmo que [`useContext()`](/apis/react/useContext) y renderizará el resultado que devuelves de esta función. Reacttambién volverá a ejecutar esta función y actualizará la interfaz de usuario siempre que el contexto pasado desde los componentes principales haya cambiado.
198
198
199
199
---
200
200
201
-
## Troubleshooting {/*troubleshooting*/}
201
+
## Solución de problemas {/*troubleshooting*/}
202
202
203
-
### I can't find a way to change the context value {/*i-cant-find-a-way-to-change-the-context-value*/}
203
+
### No puedo encontrar la manera de cambiar el valor del contexto {/*i-cant-find-a-way-to-change-the-context-value*/}
204
204
205
205
206
-
Code like this specifies the *default* context value:
206
+
Un código como este especifica el valor de contexto *predeterminado*:
207
207
208
208
```js
209
209
const ThemeContext = createContext('light');
210
210
```
211
211
212
-
This value never changes. Reactonly uses this value as a fallback if it can't find a matching provider above.
212
+
Este valor nunca cambia. Reactsolo usa este valor como respaldo si no puede encontrar un proveedor coincidente arriba.
213
213
214
-
To make context change over time, [add state and wrap components in a context provider.](/apis/react/useContext#updating-data-passed-via-context)
214
+
Para hacer que el contexto cambie con el tiempo, [agrega estado y envuelve los componentes en un proveedor de contexto.](/apis/react/useContext#updating-data-passed-via-context)
0 commit comments