From 3e682b423e3587577a07c0aae3cdb08c3f51592e Mon Sep 17 00:00:00 2001 From: Migue Martelo Date: Sat, 15 Oct 2022 10:24:27 -0500 Subject: [PATCH 1/2] translate createElement page --- beta/src/content/apis/react/createElement.md | 66 ++++++++++---------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/beta/src/content/apis/react/createElement.md b/beta/src/content/apis/react/createElement.md index 9cc74a8f1..b7bdd6d5a 100644 --- a/beta/src/content/apis/react/createElement.md +++ b/beta/src/content/apis/react/createElement.md @@ -4,7 +4,7 @@ title: createElement -`createElement` lets you create a React element. It serves as an alternative to writing [JSX.](/learn/writing-markup-with-jsx) +`createElement` te permite crear un elemento React. Sirve como alternativa a la escritura de [JSX.](/learn/writing-markup-with-jsx) ```js const element = createElement(type, props, ...children) @@ -16,13 +16,13 @@ const element = createElement(type, props, ...children) --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Creating an element without JSX {/*creating-an-element-without-jsx*/} +### Creando un elemento sin JSX {/*creating-an-element-without-jsx*/} -If you don't like [JSX](/learn/writing-markup-with-jsx) or can't use it in your project, you can use `createElement` as an alternative. +Si no te gusta [JSX](/learn/writing-markup-with-jsx) o no puedes usarlo en tu proyecto, puedes usar `createElement` como alternativa. -To create an element without JSX, call `createElement` with some type, props, and children: +Para crear un elemento sin JSX, llamas a `createElement` con type, props y children: ```js [[1, 5, "'h1'"], [2, 6, "{ className: 'greeting' }"], [3, 7, "'Hello ',"], [3, 8, "createElement('i', null, name),"], [3, 9, "'. Welcome!'"]] import { createElement } from 'react'; @@ -38,7 +38,7 @@ function Greeting({ name }) { } ``` -The children are optional, and you can pass as many as you need (the example above has three children). This code will display a `

` header with a greeting. For comparison, here is the same example rewritten with JSX: +Los children son opcionales, y puedes pasar tantos como tu necesites (el ejemplo anterior tiene tres hijos). Este código mostrará un encabezado `

` con un saludo. A modo de comparación, aquí está el mismo ejemplo reescrito con JSX: ```js [[1, 3, "h1"], [2, 3, "className=\\"greeting\\""], [3, 4, "Hello {name}. Welcome!"], [1, 5, "h1"]] function Greeting({ name }) { @@ -50,7 +50,7 @@ function Greeting({ name }) { } ``` -To render your own React component, pass a function like `Greeting` as the type instead of a string like `'h1'`: +Para renderizar tu propio componente de React, pasas una función como `Greeting` como el type en lugar de un `'h1'`: ```js [[1, 2, "Greeting"], [2, 2, "{ name: 'Taylor' }"]] export default function App() { @@ -58,7 +58,7 @@ export default function App() { } ``` -With JSX, it would look like this: +Con JSX, se vería así: ```js [[1, 2, "Greeting"], [2, 2, "name=\\"Taylor\\""]] export default function App() { @@ -66,7 +66,7 @@ export default function App() { } ``` -Here is a complete example written with `createElement`: +Aquí hay un ejemplo completo escrito con `createElement`: @@ -100,7 +100,7 @@ export default function App() { -And here is the same example written using JSX: +Y aquí está el mismo ejemplo usando JSX: @@ -127,11 +127,11 @@ export default function App() { -Both coding styles are fine, so you can use whichever one you prefer for your project. The main benefit of using JSX compared to `createElement` is that it's easy to see which closing tag corresponds to which opening tag. +Ambos estilos de código están bien, por lo que puedes usar el que prefieras para tu proyecto. El principal beneficio de usar JSX en comparación con `createElement` es que es fácil ver qué etiqueta de cierre corresponde a qué etiqueta de apertura. - + -An element is a lightweight description of a piece of the user interface. For example, both `` and `createElement(Greeting, { name: 'Taylor' })` produce an object like this: +Un elemento es una descripción ligera de una pieza de la interfaz de usuario. Por ejemplo, ambos `` y `createElement(Greeting, { name: 'Taylor' })` producen un objeto como este: ```js // Slightly simplified @@ -145,21 +145,21 @@ An element is a lightweight description of a piece of the user interface. For ex } ``` -**Note that creating this object does not render the `Greeting` component or create any DOM elements.** +**Ten en cuenta que crear este objeto no representa el componente `Greeting` o crear cualquier elemento del DOM.** -A React element is more like a description--an instruction for React to later render the `Greeting` component. By returning this object from your `App` component, you tell React what to do next. +Un elemento React es más como una descripción — una instrucción para React para luego renderizar el componente `Greeting`. Al devolver este objeto en tu componente `App`, le dices a React qué hacer a continuación. -Creating elements is extremely cheap so you don't need to try to optimize or avoid it. +Crear elementos es extremadamente barato, por lo que no necesita intentar optimizarlo o evitarlo. --- -## Reference {/*reference*/} +## Referencia {/*reference*/} ### `createElement(type, props, ...children)` {/*createelement*/} -Call `createElement` to create a React element with the given `type`, `props`, and `children`. +Llamar `createElement` para crear un elemento de React con `type`, `props`, y `children`. ```js import { createElement } from 'react'; @@ -173,31 +173,31 @@ function Greeting({ name }) { } ``` -[See more examples above.](#usage) +[Ver más ejemplos arriba.](#usage) -#### Parameters {/*parameters*/} +#### Parámetros {/*parameters*/} -* `type`: The `type` argument must be a valid React component type. For example, it could be a tag name string (such as `'div'` or `'span'`), or a React component (a function, a class, or a special component like [`Fragment`](/apis/react/Fragment)). +* `type`: El argumento `type` debe ser un tipo de componente de React válido. Por ejemplo, podría ser un string con el nombre de una etiqueta (como `'div'` o `'span'`), o un componente de React (una función, una clase, o un componente especial como [`Fragment`](/apis/react/Fragment)). -* `props`: The `props` argument must either be an object or `null`. If you pass `null`, it will be treated the same as an empty object. React will create an element with props matching the `props` you have passed. Note that `ref` and `key` from your `props` object are special and will *not* be available as `element.props.ref` and `element.props.key` on the returned `element`. They will be available as `element.ref` and `element.key`. +* `props`: El argumento `props` debe ser un objeto o `null`. Si tu le pasas `null`, será tratado igual que un objecto vacio. React creará un elemento con props que coincidan con el `props` que tu has pasado. Ten en cuenta que `ref` y `key` de tu objecto `props` son especiales y lo harán *no* estar disponible como `element.props.ref` y `element.props.key` en el `element` devuelto. Estarán disponibles como `element.ref` y `element.key`. -* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/apis/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes. +* **opcional** `...children`: Cero o más nodos. Pueden ser cualquier nodo de React, incluidos Elementos de React, strings, números, [portales](/apis/react-dom/createPortal), nodos vacíos (`null`, `undefined`, `true`, y `false`), y arreglos con nodos de React. #### Returns {/*returns*/} -`createElement` returns a React element object with a few properties: +`createElement` devuelve un objecto React element con algunas propiedades: -* `type`: The `type` you have passed. -* `props`: The `props` you have passed except for `ref` and `key`. If the `type` is a component with legacy `type.defaultProps`, then any missing or undefined `props` will get the values from `type.defaultProps`. -* `ref`: The `ref` you have passed. If missing, `null`. -* `key`: The `key` you have passed, coerced to a string. If missing, `null`. +* `type`: El `type` que pasaste. +* `props`: Los `props` que pasaste excepto `ref` y `key`. Si el `type` es un componente con `type.defaultProps` heredado, entonces cualquier `props` que falte o `props` indefinidas obtendrá los valores de `type.defaultProps`. +* `ref`: El `ref` que pasaste. Si no lo pasaste es, `null`. +* `key`: El `key` que pasaste, forzado a ser string. Si no lo pasaste es, `null`. -Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it. +Por lo general, devolverá el elemento de tu componente o lo convertirá en hijo de otro elemento. Aunque puedes leer las propiedades del elemento, es mejor tratar cada elemento como opaco después de su creación, y solo renderizarlo. -#### Caveats {/*caveats*/} +#### Advertencias {/*caveats*/} -* You must **treat React elements and their props as [immutable](https://en.wikipedia.org/wiki/Immutable_object)** and never change their contents after creation. In development, React will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) the returned element and its `props` property shallowly to enforce this. +* Debes **tratar elementos React y sus props como [immutables](https://es.wikipedia.org/wiki/Objeto_inmutable)** y nunca cambiar sus contenidos después de la creación. En desarrollo, React [congelaría](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) el elemento devuelto y su propiedad `props` para hacer cumplir esto. -* When you use JSX, **you must start a tag with a capital letter to render your own custom component.** In other words, `` is equivalent to `createElement(Something)`, but `` (lowercase) is equivalent to `createElement('something')` (note it's a string, so it will be treated as a built-in HTML tag). +* Cuando usas JSX, **debe comenzar una etiqueta con una letra mayúscula para representar tu propio componente personalizado.** En otras palabras, `` es equivalente a `createElement(Something)`, pero `` (minúscula) es equivalente a `createElement('something')` (ten encuenta que es un string, por lo que se tratará como una etiqueta de HTML normal). -* You should only **pass children as multiple arguments to `createElement` if they are all statically known,** like `createElement('h1', {}, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `createElement('ul', {}, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder. +* Solo deberías **pasar children como múltiples argumentos para `createElement` si todos son estáticamente conocidos,** como `createElement('h1', {}, child1, child2, child3)`. Si tus children son dinámicos, pasa todo el arreglo como tercer argumento: `createElement('ul', {}, listItems)`. Esto asegura que React [advertirá sobre la falta de `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) para cualquier lista dinámica. Para las listas estáticas, esto no es necesario porque nunca se reordenan. From 5356afac839fb20f54708d9e18fec4df48c3dc88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rainer=20Mart=C3=ADnez=20Fraga?= Date: Fri, 25 Nov 2022 23:34:27 -0500 Subject: [PATCH 2/2] Apply suggestions from code review --- beta/src/content/apis/react/createElement.md | 22 ++++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/beta/src/content/apis/react/createElement.md b/beta/src/content/apis/react/createElement.md index b7bdd6d5a..c231b0839 100644 --- a/beta/src/content/apis/react/createElement.md +++ b/beta/src/content/apis/react/createElement.md @@ -4,7 +4,7 @@ title: createElement -`createElement` te permite crear un elemento React. Sirve como alternativa a la escritura de [JSX.](/learn/writing-markup-with-jsx) +`createElement` te permite crear un elemento React. Sirve como alternativa a escribir [JSX.](/learn/writing-markup-with-jsx) ```js const element = createElement(type, props, ...children) @@ -18,7 +18,7 @@ const element = createElement(type, props, ...children) ## Uso {/*usage*/} -### Creando un elemento sin JSX {/*creating-an-element-without-jsx*/} +### Crear un elemento sin JSX {/*creating-an-element-without-jsx*/} Si no te gusta [JSX](/learn/writing-markup-with-jsx) o no puedes usarlo en tu proyecto, puedes usar `createElement` como alternativa. @@ -38,7 +38,7 @@ function Greeting({ name }) { } ``` -Los children son opcionales, y puedes pasar tantos como tu necesites (el ejemplo anterior tiene tres hijos). Este código mostrará un encabezado `

` con un saludo. A modo de comparación, aquí está el mismo ejemplo reescrito con JSX: +Los children son opcionales, y puedes pasar tantos como necesites (el ejemplo anterior tiene tres hijos). Este código mostrará un encabezado `

` con un saludo. A modo de comparación, aquí está el mismo ejemplo reescrito con JSX: ```js [[1, 3, "h1"], [2, 3, "className=\\"greeting\\""], [3, 4, "Hello {name}. Welcome!"], [1, 5, "h1"]] function Greeting({ name }) { @@ -50,7 +50,7 @@ function Greeting({ name }) { } ``` -Para renderizar tu propio componente de React, pasas una función como `Greeting` como el type en lugar de un `'h1'`: +Para renderizar tu propio componente de React, pasas una función como `Greeting` como el type en lugar de un string como `'h1'`: ```js [[1, 2, "Greeting"], [2, 2, "{ name: 'Taylor' }"]] export default function App() { @@ -179,25 +179,25 @@ function Greeting({ name }) { * `type`: El argumento `type` debe ser un tipo de componente de React válido. Por ejemplo, podría ser un string con el nombre de una etiqueta (como `'div'` o `'span'`), o un componente de React (una función, una clase, o un componente especial como [`Fragment`](/apis/react/Fragment)). -* `props`: El argumento `props` debe ser un objeto o `null`. Si tu le pasas `null`, será tratado igual que un objecto vacio. React creará un elemento con props que coincidan con el `props` que tu has pasado. Ten en cuenta que `ref` y `key` de tu objecto `props` son especiales y lo harán *no* estar disponible como `element.props.ref` y `element.props.key` en el `element` devuelto. Estarán disponibles como `element.ref` y `element.key`. +* `props`: El argumento `props` debe ser un objeto o `null`. Si tu le pasas `null`, será tratado igual que un objecto vacío. React creará un elemento con props que coincidan con las `props` que has pasado. Ten en cuenta que `ref` y `key` de tu objecto `props` son especiales y lo harán *no* estar disponible como `element.props.ref` y `element.props.key` en el `element` devuelto. Estarán disponibles como `element.ref` y `element.key`. -* **opcional** `...children`: Cero o más nodos. Pueden ser cualquier nodo de React, incluidos Elementos de React, strings, números, [portales](/apis/react-dom/createPortal), nodos vacíos (`null`, `undefined`, `true`, y `false`), y arreglos con nodos de React. +* **opcional** `...children`: Cero o más nodos. Pueden ser cualquier nodo de React, incluidos Elementos de React, strings, números, [portales](/apis/react-dom/createPortal), nodos vacíos (`null`, `undefined`, `true`, y `false`), y arrays con nodos de React. -#### Returns {/*returns*/} +#### Devuelve {/*returns*/} `createElement` devuelve un objecto React element con algunas propiedades: * `type`: El `type` que pasaste. * `props`: Los `props` que pasaste excepto `ref` y `key`. Si el `type` es un componente con `type.defaultProps` heredado, entonces cualquier `props` que falte o `props` indefinidas obtendrá los valores de `type.defaultProps`. -* `ref`: El `ref` que pasaste. Si no lo pasaste es, `null`. -* `key`: El `key` que pasaste, forzado a ser string. Si no lo pasaste es, `null`. +* `ref`: La `ref` que pasaste. Si no la pasaste es, `null`. +* `key`: La `key` que pasaste, forzada a ser string. Si no la pasaste es, `null`. Por lo general, devolverá el elemento de tu componente o lo convertirá en hijo de otro elemento. Aunque puedes leer las propiedades del elemento, es mejor tratar cada elemento como opaco después de su creación, y solo renderizarlo. #### Advertencias {/*caveats*/} -* Debes **tratar elementos React y sus props como [immutables](https://es.wikipedia.org/wiki/Objeto_inmutable)** y nunca cambiar sus contenidos después de la creación. En desarrollo, React [congelaría](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) el elemento devuelto y su propiedad `props` para hacer cumplir esto. +* Debes **tratar los elementos React y sus props como [inmutables](https://es.wikipedia.org/wiki/Objeto_inmutable)** y nunca cambiar sus contenidos después de creados. En desarrollo, React [congelaría](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) superficialmente el elemento devuelto y sus `props` para hacer cumplir esto. -* Cuando usas JSX, **debe comenzar una etiqueta con una letra mayúscula para representar tu propio componente personalizado.** En otras palabras, `` es equivalente a `createElement(Something)`, pero `` (minúscula) es equivalente a `createElement('something')` (ten encuenta que es un string, por lo que se tratará como una etiqueta de HTML normal). +* Cuando usas JSX, **debes comenzar una etiqueta con una letra mayúscula para renderizar tu propio componente personalizado.** En otras palabras, `` es equivalente a `createElement(Something)`, pero `` (minúscula) es equivalente a `createElement('something')` (ten encuenta que es un string, por lo que se tratará como una etiqueta de HTML normal). * Solo deberías **pasar children como múltiples argumentos para `createElement` si todos son estáticamente conocidos,** como `createElement('h1', {}, child1, child2, child3)`. Si tus children son dinámicos, pasa todo el arreglo como tercer argumento: `createElement('ul', {}, listItems)`. Esto asegura que React [advertirá sobre la falta de `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) para cualquier lista dinámica. Para las listas estáticas, esto no es necesario porque nunca se reordenan.