chore(i18n): download curriculum manually (#42835)
This commit is contained in:
committed by
GitHub
parent
2f8c5619ff
commit
fc0511bd91
@@ -11,7 +11,7 @@ dashedName: create-decimal-numbers-with-javascript
|
||||
|
||||
También podemos almacenar números decimales en variables. Los números decimales a veces se denominan números de <dfn>coma flotante</dfn> o <dfn>flotantes</dfn>.
|
||||
|
||||
**Nota:** No todos los números reales pueden representarse con precisión en <dfn>coma flotante</dfn>. Esto puede llevar a errores de redondeo. [Detalles aquí](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
|
||||
**Nota:** No todos los números reales pueden representarse con precisión en <dfn>coma flotante</dfn>. Esto puede llevar a errores de redondeo. [Detalles aquí](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems).
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@@ -8,21 +8,21 @@ dashedName: use--for-a-more-concise-conditional
|
||||
|
||||
# --description--
|
||||
|
||||
The `if/else` statements worked in the last challenge, but there's a more concise way to achieve the same result. Imagine that you are tracking several conditions in a component and you want different elements to render depending on each of these conditions. If you write a lot of `else if` statements to return slightly different UIs, you may repeat code which leaves room for error. Instead, you can use the `&&` logical operator to perform conditional logic in a more concise way. This is possible because you want to check if a condition is `true`, and if it is, return some markup. Here's an example:
|
||||
Las sentencias `if/else` funcionaron en el último desafío, pero hay una manera más concisa de lograr el mismo resultado. Imagina que estás rastreando varias condiciones en un componente y deseas que diferentes elementos se rendericen dependiendo de cada una de estas condiciones. Si escribes un montón de sentencias `else if` para devolver UIs ligeramente diferentes, puedes repetir código que deja espacio para el error. En su lugar, puedes usar el operador lógico `&&` para realizar lógica condicional de una manera más concisa. Esto es posible porque quieres comprobar si una condición es `true`, y si es así, devuelve algún código. Aquí hay un ejemplo:
|
||||
|
||||
```jsx
|
||||
{condition && <p>markup</p>}
|
||||
```
|
||||
|
||||
If the `condition` is `true`, the markup will be returned. If the condition is `false`, the operation will immediately return `false` after evaluating the `condition` and return nothing. You can include these statements directly in your JSX and string multiple conditions together by writing `&&` after each one. This allows you to handle more complex conditional logic in your `render()` method without repeating a lot of code.
|
||||
Si la `condition` es `true`, el código será devuelto. Si la condición es `false`, la operación devolverá inmediatamente `false` después de evaluar la `condition` y no devolverá nada. Puedes incluir estas sentencias directamente en tu JSX y encadenar varias condiciones juntas escribiendo `&&` después de cada uno. Esto te permite manejar una lógica condicional más compleja en tu método `render()` sin repetir un montón de código.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Solve the previous example again, so the `h1` only renders if `display` is `true`, but use the `&&` logical operator instead of an `if/else` statement.
|
||||
Resuelve el ejemplo anterior de nuevo, de este modo el `h1` solo renderiza si `display` es `true`, pero usa el operador lógico `&&` en lugar de una sentencia `if/else`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`MyComponent` should exist and render.
|
||||
`MyComponent` debe existir y renderizar.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -33,7 +33,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
When `display` is set to `true`, a `div`, `button`, and `h1` should render.
|
||||
Cuando `display` se establece en `true`, un `div`, `button`, y `h1` debe renderizarse.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@@ -54,7 +54,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
When `display` is set to `false`, only a `div` and `button` should render.
|
||||
Cuando `display` se establece en `false`, solo un `div` y un `button` debe renderizarse.
|
||||
|
||||
```js
|
||||
async () => {
|
||||
@@ -75,7 +75,7 @@ async () => {
|
||||
};
|
||||
```
|
||||
|
||||
The render method should use the `&&` logical operator to check the condition of `this.state.display`.
|
||||
El método renderizador debe usar el operador lógico `&&` para comprobar la condición de `this.state.display`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').includes('&&'));
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036187
|
||||
title: Use a Ternary Expression for Conditional Rendering
|
||||
title: Utiliza una expresión ternaria para el renderizado condicional
|
||||
challengeType: 6
|
||||
forumTopicId: 301414
|
||||
dashedName: use-a-ternary-expression-for-conditional-rendering
|
||||
@@ -8,7 +8,7 @@ dashedName: use-a-ternary-expression-for-conditional-rendering
|
||||
|
||||
# --description--
|
||||
|
||||
Before moving on to dynamic rendering techniques, there's one last way to use built-in JavaScript conditionals to render what you want: the <dfn>ternary operator</dfn>. The ternary operator is often utilized as a shortcut for `if/else` statements in JavaScript. They're not quite as robust as traditional `if/else` statements, but they are very popular among React developers. One reason for this is because of how JSX is compiled, `if/else` statements can't be inserted directly into JSX code. You might have noticed this a couple challenges ago — when an `if/else` statement was required, it was always *outside* the `return` statement. Ternary expressions can be an excellent alternative if you want to implement conditional logic within your JSX. Recall that a ternary operator has three parts, but you can combine several ternary expressions together. Here's the basic syntax:
|
||||
Antes de pasar a técnicas de renderizado dinámico, hay una última forma de usar condicionales de JavaScript incorporados para representar lo que quieres: el <dfn>operador ternario</dfn>. El operador ternario a menudo es utilizado como un acceso directo para las sentencias `if/else` en JavaScript. No son tan robustas como las sentencias tradicionales `if/else`, pero son muy populares entre los desarrolladores de React. Una de las razones de esto es debido a cómo se compila JSX, las sentencias `if/else` no se pueden insertar directamente en el código JSX. Puede que hayas notado esto hace un par de desafíos, cuando se requirió una sentencia `if/else`, siempre estaba *fuera* de la sentencia `return`. Las expresiones ternarias pueden ser una excelente alternativa si deseas implementar lógica condicional dentro de tu JSX. Recuerda que un operador ternario tiene tres partes, pero puedes combinar varias expresiones ternarias juntas. Aquí está la sintaxis básica:
|
||||
|
||||
```jsx
|
||||
condition ? expressionIfTrue : expressionIfFalse;
|
||||
@@ -16,13 +16,13 @@ condition ? expressionIfTrue : expressionIfFalse;
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has three constants defined within the `CheckUserAge` component's `render()` method. They are called `buttonOne`, `buttonTwo`, and `buttonThree`. Each of these is assigned a simple JSX expression representing a button element. First, initialize the state of `CheckUserAge` with `input` and `userAge` both set to values of an empty string.
|
||||
El editor de código tiene tres constantes definidas dentro del método `render()` del componente `CheckUserAge`. Estas se llaman `buttonOne`, `buttonTwo` y `buttonThree`. A cada una de estas se le asigna una expresión JSX simple que representa un elemento de botón. Primero, inicializa el estado de `CheckUserAge` con `input` y `userAge` ambos configurados a valores de una cadena vacía.
|
||||
|
||||
Once the component is rendering information to the page, users should have a way to interact with it. Within the component's `return` statement, set up a ternary expression that implements the following logic: when the page first loads, render the submit button, `buttonOne`, to the page. Then, when a user enters their age and clicks the button, render a different button based on the age. If a user enters a number less than `18`, render `buttonThree`. If a user enters a number greater than or equal to `18`, render `buttonTwo`.
|
||||
Una vez que el componente está renderizando información a la página, los usuarios deberían tener una forma de interactuar con ella. Dentro de la declaración `return` del componente, configura una expresión ternaria que implementa la siguiente lógica: cuando la página carga por primera vez, renderiza el botón de envío, `buttonOne`, a la página. Luego, cuando un usuario ingrese su edad y haga clic en el botón, renderiza un botón diferente basado en la edad. Si un usuario introduce un número menor que `18`, renderiza `buttonThree`. Si un usuario introduce un número mayor o igual a `18`, renderiza `buttonTwo`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `CheckUserAge` component should render with a single `input` element and a single `button` element.
|
||||
El componente `CheckUserAge` debe renderizarse con un solo elemento `input` y un solo elemento `button`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -33,7 +33,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `CheckUserAge` component's state should be initialized with a property of `userAge` and a property of `input`, both set to a value of an empty string.
|
||||
El estado del componente `CheckUserAge` debe inicializarse con una propiedad de `userAge` y una propiedad de `input`, ambos establecidos a un valor de una cadena vacía.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
When the `CheckUserAge` component is first rendered to the DOM, the `button`'s inner text should be Submit.
|
||||
Cuando el componente `CheckUserAge` es renderizado por primera vez en el DOM, el texto interno del `button` debe decir "Submit".
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -51,7 +51,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
When a number of less than 18 is entered into the `input` element and the `button` is clicked, the `button`'s inner text should read `You Shall Not Pass`.
|
||||
Cuando se introduce un número menor de 18 en el elemento `input` y se hace clic en el `button`, el texto interno del `button` debe decir `You Shall Not Pass`.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
@@ -83,7 +83,7 @@ When a number of less than 18 is entered into the `input` element and the `butto
|
||||
})();
|
||||
```
|
||||
|
||||
When a number greater than or equal to 18 is entered into the `input` element and the `button` is clicked, the `button`'s inner text should read `You May Enter`.
|
||||
Cuando se introduce un número mayor o igual a 18 en el elemento `input` y se hace clic en el `button` el texto interno del `button` debe decir `You May Enter`.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
@@ -115,7 +115,7 @@ When a number greater than or equal to 18 is entered into the `input` element an
|
||||
})();
|
||||
```
|
||||
|
||||
Once a number has been submitted, and the value of the `input` is once again changed, the `button` should return to reading `Submit`.
|
||||
Una vez que un número ha sido enviado, y el valor del `input` se cambia una vez más, el `button` debe decir `Submit`.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
@@ -156,7 +156,7 @@ Once a number has been submitted, and the value of the `input` is once again cha
|
||||
})();
|
||||
```
|
||||
|
||||
Your code should not contain any `if/else` statements.
|
||||
Tu código no debe contener ninguna sentencia `if/else`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036183
|
||||
title: Use Advanced JavaScript in React Render Method
|
||||
title: Usa JavaScript avanzado en el método render de React
|
||||
challengeType: 6
|
||||
forumTopicId: 301415
|
||||
dashedName: use-advanced-javascript-in-react-render-method
|
||||
@@ -8,17 +8,17 @@ dashedName: use-advanced-javascript-in-react-render-method
|
||||
|
||||
# --description--
|
||||
|
||||
In previous challenges, you learned how to inject JavaScript code into JSX code using curly braces, `{ }`, for tasks like accessing props, passing props, accessing state, inserting comments into your code, and most recently, styling your components. These are all common use cases to put JavaScript in JSX, but they aren't the only way that you can utilize JavaScript code in your React components.
|
||||
En desafíos anteriores, aprendiste cómo inyectar código JavaScript en código JSX usando llaves, `{ }`, para tareas como acceder a props, pasar props, acceder al state, insertar comentarios en tu código y, más recientemente, diseñar tus componentes. Todos estos son casos de uso común para poner JavaScript en JSX, pero no son la única manera de utilizar código JavaScript en tus componentes React.
|
||||
|
||||
You can also write JavaScript directly in your `render` methods, before the `return` statement, ***without*** inserting it inside of curly braces. This is because it is not yet within the JSX code. When you want to use a variable later in the JSX code *inside* the `return` statement, you place the variable name inside curly braces.
|
||||
También puedes escribir JavaScript directamente en los métodos `render`, antes de la sentencia `return`, ***sin*** insertarlo dentro de llaves. Esto es porque aún no está dentro del código JSX. Cuando quieras utilizar una variable en el código JSX *dentro* de la sentencia `return`, colocas el nombre de la variable dentro de llaves.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In the code provided, the `render` method has an array that contains 20 phrases to represent the answers found in the classic 1980's Magic Eight Ball toy. The button click event is bound to the `ask` method, so each time the button is clicked a random number will be generated and stored as the `randomIndex` in state. On line 52, delete the string `change me!` and reassign the `answer` const so your code randomly accesses a different index of the `possibleAnswers` array each time the component updates. Finally, insert the `answer` const inside the `p` tags.
|
||||
En el código proporcionado, el método `render` tiene un arreglo que contiene 20 frases para representar las respuestas encontradas en el clásico juego "Magic Eight Ball" de los años ochenta. El evento clic del botón está vinculado al método `ask`, por lo que cada vez que se haga clic en el botón se generará un número aleatorio y se almacenará como el `randomIndex` en el state. En la línea 52, elimina la cadena `change me!` y reasigna la constante `answer` para que tu código acceda aleatoriamente a un índice diferente del arreglo `possibleAnswers` cada vez que se actualiza el componente. Finalmente, inserta la constante `answer` dentro de las etiquetas `p`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `MagicEightBall` component should exist and should render to the page.
|
||||
El componente `MagicEightBall` debe existir y renderizarse en la página.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@@ -28,7 +28,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`MagicEightBall`'s first child should be an `input` element.
|
||||
El primer elemento hijo de `MagicEightBall` debe ser un elemento `input`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@@ -40,7 +40,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`MagicEightBall`'s third child should be a `button` element.
|
||||
El tercer elemento hijo de `MagicEightBall` debe ser un elemento `button`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@@ -52,7 +52,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`MagicEightBall`'s state should be initialized with a property of `userInput` and a property of `randomIndex` both set to a value of an empty string.
|
||||
El estado de `MagicEightBall` debe inicializarse con una propiedad de `userInput` y una propiedad de `randomIndex` juntas establecidas como cadenas de texto vacías.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
When `MagicEightBall` is first mounted to the DOM, it should return an empty `p` element.
|
||||
Cuando `MagicEightBall` se monte por primera vez en el DOM, debe devolver un elemento `p` vacío.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -71,7 +71,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
When text is entered into the `input` element and the button is clicked, the `MagicEightBall` component should return a `p` element that contains a random element from the `possibleAnswers` array.
|
||||
Cuando se introduce texto en el elemento `input` y se hace clic en el botón, el componente `MagicEightBall` debe devolver un elemento `p` que contiene un elemento aleatorio del arreglo `possibleAnswers`.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403618c
|
||||
title: Use Array.filter() to Dynamically Filter an Array
|
||||
title: Usa Array.filter() para filtrar dinámicamente un arreglo
|
||||
challengeType: 6
|
||||
forumTopicId: 301416
|
||||
dashedName: use-array-filter-to-dynamically-filter-an-array
|
||||
@@ -8,7 +8,7 @@ dashedName: use-array-filter-to-dynamically-filter-an-array
|
||||
|
||||
# --description--
|
||||
|
||||
The `map` array method is a powerful tool that you will use often when working with React. Another method related to `map` is `filter`, which filters the contents of an array based on a condition, then returns a new array. For example, if you have an array of users that all have a property `online` which can be set to `true` or `false`, you can filter only those users that are online by writing:
|
||||
El método de arreglo `map` es una potente herramienta que puedes usar a menudo al trabajar con React. Otro método relacionado con `map` es `filter`, que filtra el contenido de un arreglo basado en una condición, luego devuelve un nuevo arreglo. Por ejemplo, si tienes un arreglo de usuarios que todos tienen una propiedad `online` que puede establecerse en `true` o `false`, puedes filtrar sólo aquellos usuarios que estén en línea escribiendo:
|
||||
|
||||
```js
|
||||
let onlineUsers = users.filter(user => user.online);
|
||||
@@ -16,11 +16,11 @@ let onlineUsers = users.filter(user => user.online);
|
||||
|
||||
# --instructions--
|
||||
|
||||
In the code editor, `MyComponent`'s `state` is initialized with an array of users. Some users are online and some aren't. Filter the array so you see only the users who are online. To do this, first use `filter` to return a new array containing only the users whose `online` property is `true`. Then, in the `renderOnline` variable, map over the filtered array, and return a `li` element for each user that contains the text of their `username`. Be sure to include a unique `key` as well, like in the last challenges.
|
||||
En el editor de código, el `state` de `MyComponent` es inicializado con un arreglo de usuarios. Algunos usuarios están conectados y otros no. Filtra el arreglo para que sólo veas a los usuarios que están en línea. Para hacer esto, primero usa `filter` para devolver un nuevo arreglo que contiene solo a los usuarios cuya propiedad `online` es `true`. Luego, en la variable `renderOnline`, asigna sobre el arreglo filtrado, y devuelve un elemento `li` para cada usuario que contiene el texto de su `username`. Asegúrate de incluir también una única `key`, como en los últimos desafíos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`MyComponent` should exist and render to the page.
|
||||
`MyComponent` debe existir y renderizarse en la página.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@@ -29,7 +29,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`MyComponent`'s state should be initialized to an array of six users.
|
||||
El estado de `MyComponent` debe inicializarse a un arreglo de seis usuarios.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -40,7 +40,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`MyComponent` should return a `div`, an `h1`, and then an unordered list containing `li` elements for every user whose online status is set to `true`.
|
||||
`MyComponent` debe devolver un `div`, un `h1`, y luego una lista desordenada que contiene elementos `li` para cada usuario cuyo estado de conexión se establece en `true`.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
@@ -83,7 +83,7 @@ assert(
|
||||
})();
|
||||
```
|
||||
|
||||
`MyComponent` should render `li` elements that contain the `username` of each online user.
|
||||
`MyComponent` debe renderizar elementos `li` que contienen el `username` de cada usuario en línea.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
@@ -109,7 +109,7 @@ assert(
|
||||
})();
|
||||
```
|
||||
|
||||
Each list item element should have a unique `key` attribute.
|
||||
Cada elemento de la lista debe tener un atributo `key` único.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403618a
|
||||
title: Use Array.map() to Dynamically Render Elements
|
||||
title: Utiliza Array.map() para renderizar dinámicamente los elementos
|
||||
challengeType: 6
|
||||
forumTopicId: 301417
|
||||
dashedName: use-array-map-to-dynamically-render-elements
|
||||
@@ -8,21 +8,21 @@ dashedName: use-array-map-to-dynamically-render-elements
|
||||
|
||||
# --description--
|
||||
|
||||
Conditional rendering is useful, but you may need your components to render an unknown number of elements. Often in reactive programming, a programmer has no way to know what the state of an application is until runtime, because so much depends on a user's interaction with that program. Programmers need to write their code to correctly handle that unknown state ahead of time. Using `Array.map()` in React illustrates this concept.
|
||||
El renderizado condicional es útil, pero es posible que necesites tus componentes para renderizar un número desconocido de elementos. A menudo en la programación reactiva, un programador no tiene forma de saber cuál es el estado de una aplicación hasta el tiempo de ejecución, porque mucho depende de la interacción de un usuario con ese programa. Los programadores necesitan escribir su código para manejar correctamente ese estado desconocido antes de tiempo. Usar `Array.map()` en React ilustra este concepto.
|
||||
|
||||
For example, you create a simple "To Do List" app. As the programmer, you have no way of knowing how many items a user might have on their list. You need to set up your component to dynamically render the correct number of list elements long before someone using the program decides that today is laundry day.
|
||||
Por ejemplo, crea una aplicación simple "To Do List". Como programador, no tienes forma de saber cuántos elementos puede tener un usuario en su lista. Necesitas configurar tu componente para renderizar dinámicamente el número correcto de elementos de la lista mucho antes de que alguien que use el programa decida que hoy es día de lavandería.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor has most of the `MyToDoList` component set up. Some of this code should look familiar if you completed the controlled form challenge. You'll notice a `textarea` and a `button`, along with a couple of methods that track their states, but nothing is rendered to the page yet.
|
||||
El editor de código tiene la mayoría del componente `MyToDoList` configurado. Parte de este código debería parecer familiar si completaste el desafío de formulario controlado. Vas a notar un `textarea` y un `button`, junto con un par de métodos que rastrean sus estados, pero aún no se muestra nada a la página.
|
||||
|
||||
Inside the `constructor`, create a `this.state` object and define two states: `userInput` should be initialized as an empty string, and `toDoList` should be initialized as an empty array. Next, delete the comment in the `render()` method next to the `items` variable. In its place, map over the `toDoList` array stored in the component's internal state and dynamically render a `li` for each item. Try entering the string `eat, code, sleep, repeat` into the `textarea`, then click the button and see what happens.
|
||||
Dentro del `constructor`, crea un objeto `this.state` y define dos estados: `userInput` que debe inicializarse como una cadena vacía, y `toDoList` que debe inicializarse como un arreglo vacío. Luego, elimina el comentario junto a la variable `items` del método `render()`. En su lugar, utiliza la función map() para recorrer el arreglo `toDoList` almacenado en el internal state del componente y renderizar un `li` por cada item. Intenta introducir la cadena `eat, code, sleep, repeat` dentro del `textarea`, haz clic en el botón y ve qué sucede.
|
||||
|
||||
**Note:** You may know that all sibling child elements created by a mapping operation like this do need to be supplied with a unique `key` attribute. Don't worry, this is the topic of the next challenge.
|
||||
**Nota:** Puede que sepas que todos los elementos hijos hermanos creados por una operación map como ésta necesitan poseer un atributo `key` único. No te preocupes, este es el tema de nuestro próximo desafío.
|
||||
|
||||
# --hints--
|
||||
|
||||
The MyToDoList component should exist and render to the page.
|
||||
El componente MyToDoList debe existir y mostrarse en la página.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -33,7 +33,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The first child of `MyToDoList` should be a `textarea` element.
|
||||
El primer hijo de `MyToDoList` debe ser un elemento `textarea`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -47,7 +47,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The second child of `MyToDoList` should be a `br` element.
|
||||
El segundo hijo de `MyToDoList` debe ser un elemento `br`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -60,7 +60,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The third child of `MyToDoList` should be a `button` element.
|
||||
El tercer hijo de `MyToDoList` debe ser un elemento `button`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -74,7 +74,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The state of `MyToDoList` should be initialized with `toDoList` as an empty array.
|
||||
El estado de `MyToDoList` debe inicializarse con un arreglo vacío `toDoList`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -89,7 +89,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The state of `MyToDoList` should be initialized with `userInput` as an empty string.
|
||||
El estado de `MyToDoList` debe ser inicializado con una cadena vacía `userInput`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -104,7 +104,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
When the `Create List` button is clicked, the `MyToDoList` component should dynamically return an unordered list that contains a list item element for every item of a comma-separated list entered into the `textarea` element.
|
||||
Cuando el botón `Create List` es presionado, el componente `MyToDoList` debe devolver dinámicamente una lista desordenada que contenga un artículo por cada elemento de una lista separada por coma dentro del elemento `textarea`.
|
||||
|
||||
```js
|
||||
(() => {
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403616b
|
||||
title: Use Default Props
|
||||
title: Usa props predeterminadas
|
||||
challengeType: 6
|
||||
forumTopicId: 301418
|
||||
dashedName: use-default-props
|
||||
@@ -8,15 +8,15 @@ dashedName: use-default-props
|
||||
|
||||
# --description--
|
||||
|
||||
React also has an option to set default props. You can assign default props to a component as a property on the component itself and React assigns the default prop if necessary. This allows you to specify what a prop value should be if no value is explicitly provided. For example, if you declare `MyComponent.defaultProps = { location: 'San Francisco' }`, you have defined a location prop that's set to the string `San Francisco`, unless you specify otherwise. React assigns default props if props are undefined, but if you pass `null` as the value for a prop, it will remain `null`.
|
||||
React también tiene una opción para establecer props predeterminadas. Puedes asignar props predeterminadas a un componente como si fueran una propiedad dentro del propio componente y React asigna la prop predeterminada si es necesario. Esto te permite especificar cuál debe ser el valor de una prop si no se provee un valor específico. Por ejemplo, si declaras `MyComponent.defaultProps = { location: 'San Francisco' }`, has definido una prop de localización que se establece en la cadena `San Francisco`, a menos que especifiques lo contrario. React asigna props predeterminadas si estas no están definidas, pero si pasas el valor `null` como valor para una prop, este permanecerá `null`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code editor shows a `ShoppingCart` component. Define default props on this component which specify a prop `items` with a value of `0`.
|
||||
El editor de código muestra un componente `ShoppingCart`. Define props predeterminadas en este componente que especifican una prop `items` con un valor de `0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `ShoppingCart` component should render.
|
||||
El componente `ShoppingCart` debe renderizarse.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -27,7 +27,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `ShoppingCart` component should have a default prop of `{ items: 0 }`.
|
||||
El componente `ShoppingCart` debe tener una prop predeterminada de `{ items: 0 }`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d403616d
|
||||
title: Use PropTypes to Define the Props You Expect
|
||||
title: Usa PropTypes para definir las props que esperas
|
||||
challengeType: 6
|
||||
forumTopicId: 301419
|
||||
dashedName: use-proptypes-to-define-the-props-you-expect
|
||||
@@ -8,25 +8,25 @@ dashedName: use-proptypes-to-define-the-props-you-expect
|
||||
|
||||
# --description--
|
||||
|
||||
React provides useful type-checking features to verify that components receive props of the correct type. For example, your application makes an API call to retrieve data that you expect to be in an array, which is then passed to a component as a prop. You can set `propTypes` on your component to require the data to be of type `array`. This will throw a useful warning when the data is of any other type.
|
||||
React proporciona características útiles de validación de tipos para verificar que los componentes reciban las props del tipo correcto. Por ejemplo, tu aplicación hace una llamada a un API para obtener datos que se esperan que sea un arreglo, el cual es pasado al componente como una prop. Puedes establecer `propTypes` en tu componente para que los datos sean de tipo `array`. Esto arrojará una advertencia útil cuando los datos sean de otro tipo.
|
||||
|
||||
It's considered a best practice to set `propTypes` when you know the type of a prop ahead of time. You can define a `propTypes` property for a component in the same way you defined `defaultProps`. Doing this will check that props of a given key are present with a given type. Here's an example to require the type `function` for a prop called `handleClick`:
|
||||
Se considera una muy buena práctica definir los `propTypes` cuando conoces el tipo de una propiedad con antelación. Puedes definir una propiedad `propTypes` para un componente de la misma manera que defines `defaultProps`. Al hacer esto, se validará que las props de una clave determinada están presentes con un tipo específico. Aquí hay un ejemplo para validar el tipo `function` para una prop llamada `handleClick`:
|
||||
|
||||
```js
|
||||
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
|
||||
```
|
||||
|
||||
In the example above, the `PropTypes.func` part checks that `handleClick` is a function. Adding `isRequired` tells React that `handleClick` is a required property for that component. You will see a warning if that prop isn't provided. Also notice that `func` represents `function`. Among the seven JavaScript primitive types, `function` and `boolean` (written as `bool`) are the only two that use unusual spelling. In addition to the primitive types, there are other types available. For example, you can check that a prop is a React element. Please refer to the [documentation](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type) for all of the options.
|
||||
En el ejemplo anterior, la parte de `PropTypes.func` verifica que `handleClick` es una función. Añadir `isRequired` le dice a React que `handleClick` es una propiedad obligatoria para ese componente. Verás una advertencia si no se proporciona esa propiedad. También ten en cuenta que `func` representa `function`. Entre los siete tipos primitivos de JavaScript, `function` y `boolean` (escrito como `bool`) son los únicos dos que utilizan ortografía diferente. Además de los tipos primitivos, hay otros tipos disponibles. Por ejemplo, puedes validar si una prop es un elemento React. Por favor, consulta la [documentación](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type) para todas las opciones.
|
||||
|
||||
**Note:** As of React v15.5.0, `PropTypes` is imported independently from React, like this: `import PropTypes from 'prop-types';`
|
||||
**Nota:** A partir de React v15.5.0, `PropTypes` se importa de manera independiente de React, así: `import PropTypes from 'prop-types';`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Define `propTypes` for the `Items` component to require `quantity` as a prop and verify that it is of type `number`.
|
||||
Define `propTypes` para el componente `Items` de tal manera que `quantity` sea una prop obligatoria y verificar que sea de tipo `number`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `ShoppingCart` component should render.
|
||||
El componente `ShoppingCart` debe renderizarse.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -37,7 +37,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Items` component should render.
|
||||
El componente `Items` debe renderizarse.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Items` component should include a `propTypes` check to require a value for `quantity` and ensure that its value is a number.
|
||||
El componente `Items` debe incluir una comprobación `propTypes` para requerir un valor para `quantity` y asegurar que su valor es un número.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a24c314108439a4d4036165
|
||||
title: Use React to Render Nested Components
|
||||
title: Utiliza React para procesar componentes anidados
|
||||
challengeType: 6
|
||||
forumTopicId: 301420
|
||||
dashedName: use-react-to-render-nested-components
|
||||
@@ -8,23 +8,23 @@ dashedName: use-react-to-render-nested-components
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge showed a simple way to compose two components, but there are many different ways you can compose components with React.
|
||||
El último desafío mostró una manera simple de organizar dos componentes, pero hay muchas maneras diferentes de organizar componentes con React.
|
||||
|
||||
Component composition is one of React's powerful features. When you work with React, it is important to start thinking about your user interface in terms of components like the App example in the last challenge. You break down your UI into its basic building blocks, and those pieces become the components. This helps to separate the code responsible for the UI from the code responsible for handling your application logic. It can greatly simplify the development and maintenance of complex projects.
|
||||
La composición de componentes es una de las características más poderosas de React. Cuando trabajas con React, es importante comenzar a pensar en tu interfaz de usuario en términos de componentes, como el ejemplo App del último desafío. Debes dividir tu UI en sus bloques básicos de construcción, y esas piezas se convierten en los componentes. Esto ayuda a separar el código responsable de la interfaz de usuario del código responsable de manejar la lógica de tu aplicación. Esto puede simplificar enormemente el desarrollo y el mantenimiento de proyectos complejos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
There are two functional components defined in the code editor, called `TypesOfFruit` and `Fruits`. Take the `TypesOfFruit` component and compose it, or *nest* it, within the `Fruits` component. Then take the `Fruits` component and nest it within the `TypesOfFood` component. The result should be a child component, nested within a parent component, which is nested within a parent component of its own!
|
||||
Hay dos componentes funcionales definidos en el editor de código, llamados `TypesOfFruit` y `Fruits`. Toma el componente `TypesOfFruit` y organízalo, o *anídalo*, dentro del componente `Fruits`. Luego toma el componente `Fruits` y anídalo dentro del componente `TypesOfFood`. El resultado debe ser un componente hijo, anidado dentro de un componente padre, ¡que a su vez está anidado dentro de un componente padre!
|
||||
|
||||
# --hints--
|
||||
|
||||
The `TypesOfFood` component should return a single `div` element.
|
||||
El componente `TypesOfFood` debe devolver un solo elemento `div`.
|
||||
|
||||
```js
|
||||
assert(Enzyme.shallow(React.createElement(TypesOfFood)).type() === 'div');
|
||||
```
|
||||
|
||||
The `TypesOfFood` component should return the `Fruits` component.
|
||||
El componente `TypesOfFood` debe devolver el componente `Fruits`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -33,7 +33,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `Fruits` component should return the `TypesOfFruit` component.
|
||||
El componente `Fruits` debe devolver el componente `TypesOfFruit`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `TypesOfFruit` component should return the `h2` and `ul` elements.
|
||||
El componente `TypesOfFruit` debe devolver los elementos `h2` y `ul`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@@ -26,9 +26,11 @@ As you can see, the body is encoded like the query string. This is the default f
|
||||
|
||||
# --instructions--
|
||||
|
||||
Install the `body-parser` module in your `package.json`. Then, `require` it at the top of the file. Store it in a variable named `bodyParser`. The middleware to handle urlencoded data is returned by `bodyParser.urlencoded({extended: false})`. Pass to `app.use()` the function returned by the previous method call. As usual, the middleware must be mounted before all the routes which need it.
|
||||
Install the `body-parser` module in your `package.json`. Then, `require` it at the top of the file. Store it in a variable named `bodyParser`. The middleware to handle urlencoded data is returned by `bodyParser.urlencoded({extended: false})`. Pass the function returned by the previous method call to `app.use()`. As usual, the middleware must be mounted before all the routes that depend on it.
|
||||
|
||||
**Note:** `extended=false` is a configuration option that tells the parser to use the classic encoding. When using it, values can be only strings or arrays. The extended version allows more data flexibility, but it is outmatched by JSON.
|
||||
**Note:** `extended` is a configuration option that tells `body-parser` which parsing needs to be used. When `extended=false` it uses the classic encoding `querystring` library. When `extended=true` it uses `qs` library for parsing.
|
||||
|
||||
When using `extended=false`, values can be only strings or arrays. The object returned when using `querystring` does not prototypically inherit from the default JavaScript `Object`, which means functions like `hasOwnProperty`, `toString` will not be available. The extended version allows more data flexibility, but it is outmatched by JSON.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
Reference in New Issue
Block a user