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
Copy file name to clipboardExpand all lines: content/docs/reference-dom-elements.md
+38-38
Original file line number
Diff line number
Diff line change
@@ -14,27 +14,28 @@ redirect_from:
14
14
- "tips/dangerously-set-inner-html.html"
15
15
---
16
16
17
-
React implements a browser-independent DOM system for performance and cross-browser compatibility. We took the opportunity to clean up a few rough edges in browser DOM implementations.
17
+
React implementa un sistema DOM independiente del navegador, por motivos de rendimiento y compatibilidad entre navegadores. Esto nos dio la oportunidad de pulir algunos detalles en las implementaciones del DOM en el navegador.
18
18
19
-
In React, all DOM properties and attributes (including event handlers) should be camelCased. For example, the HTML attribute `tabindex`corresponds to the attribute `tabIndex`in React. The exception is`aria-*`and`data-*`attributes, which should be lowercased. For example, you can keep`aria-label`as `aria-label`.
19
+
En React, todas las propiedades y atributos (incluidos los manejadores de eventos) deben escribirse en estilo *camelCase*. Por ejemplo, el atributo HTML `tabindex`corresponde al atributo `tabIndex`en React. Los atributos tipo`aria-*`y`data-*`son la excepción y deben escribirse en minúsculas. Por ejemplo,`aria-label`en HTML también es `aria-label` en React.
20
20
21
-
## Differences In Attributes
21
+
## Diferencias en los atributos
22
22
23
-
There are a number of attributes that work differently between React and HTML:
23
+
Hay una serie de atributos HTML que funcionan de manera diferente en React.
24
24
25
25
### checked
26
26
27
-
The `checked`attribute is supported by `<input>`components of type `checkbox`or`radio`. You can use it to set whether the component is checked. This is useful for building controlled components. `defaultChecked`is the uncontrolled equivalent, which sets whether the component is checked when it is first mounted.
27
+
El atributo `checked`es compatible con los componentes `<input>`tipo `checkbox`o`radio`. Lo puedes usar para establecer si el componente está marcado. Esto es útil para construir componentes controlados. `defaultChecked`es el equivalente no controlado; solo establece si el componente está marcado cuando se monta por primera vez.
28
28
29
29
### className
30
30
31
-
To specify a CSS class, use the `className` attribute. This applies to all regular DOM and SVG elements like `<div>`, `<a>`, and others.
31
+
Para especificar una clase CSS, usa el atributo `className`. Esto aplica a todos los elementos regulares de DOM y SVG como `<div>`, `<a>`, y otros.
32
32
33
-
If you use React with Web Components (which is uncommon), use the `class`attribute instead.
33
+
Si usas React con Web Components (lo cual no es común), usa el atributo `class`en lugar de `className`.
34
34
35
35
### dangerouslySetInnerHTML
36
36
37
-
`dangerouslySetInnerHTML` is React's replacement for using `innerHTML` in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) attack. So, you can set HTML directly from React, but you have to type out `dangerouslySetInnerHTML` and pass an object with a `__html` key, to remind yourself that it's dangerous. For example:
37
+
En React, `dangerouslySetInnerHTML` es el atributo que reemplaza a `innerHTML` (propiedad DOM). Significa "establecer HTML interno peligrosamente". En general, es riesgoso establecer contenido HTML desde el código, porque puedes exponer inadvertidamente a tus usuarios a un ataque [*cross-site scripting* (XSS)](https://es.wikipedia.org/wiki/Cross-site_scripting). Por lo tanto, para establecer contenido HTML directamente desde React, debes usar el atributo `dangerouslySetInnerHTML` y pasarle un objeto con una propiedad `__html`, como recordatorio de que es peligroso. Por ejemplo:
38
+
38
39
39
40
```js
40
41
functioncreateMarkup() {
@@ -48,23 +49,23 @@ function MyComponent() {
48
49
49
50
### htmlFor
50
51
51
-
Since `for`is a reserved word in JavaScript, React elements use `htmlFor`instead.
52
+
Ya que `for`es una palabra reservada en Javascript, los elementos de React usan el atributo `htmlFor`en su lugar.
52
53
53
54
### onChange
54
55
55
-
The `onChange`event behaves as you would expect it to: whenever a form field is changed, this event is fired. We intentionally do not use the existing browser behavior because`onChange`is a misnomer for its behavior and React relies on this event to handle user input in real time.
56
+
El evento `onChange`se comporta según lo esperado: cuando el campo de un formulario cambia, se lanza el evento. No usamos intencionalmente el comportamiento existente en los navegadores, porque`onChange`no es un nombre adecuado para lo que hace y React depende de este evento para manejar la entrada del usuario en tiempo real.
56
57
57
58
### selected
58
59
59
-
The `selected`attribute is supported by `<option>` components. You can use it to set whether the component is selected. This is useful for building controlled components.
60
+
El atributo `selected`es compatible con los componentes tipo `<option>`. Puedes usarlo para establecer si el elemento está seleccionado, lo cual es útil para construir componentes controlados.
60
61
61
62
### style
62
63
63
-
>Note
64
+
>Nota
64
65
>
65
-
>Some examples in the documentation use `style`for convenience, but**using the `style` attribute as the primary means of styling elements is generally not recommended.** In most cases, [`className`](#classname)should be used to reference classes defined in an external CSS stylesheet. `style`is most often used in React applications to add dynamically-computed styles at render time. See also[FAQ: Styling and CSS](/docs/faq-styling.html).
66
+
>Algunos ejemplos en la documentación usan el atributo `style`por conveniencia, pero**generalmente no se recomienda usar el atributo `style` como medio principal para estilizar elementos**. En la mayoría de los casos, [`className`](#classname)debe ser usado para hacer referencia a clases definidas en documentos CSS externos. En React, el atributo `style`se usa con mayor frecuencia para añadir estilos calculados dinámicamente al momento de renderización. Revisa tambièn[FAQ: Styling and CSS](/docs/faq-styling.html).
66
67
67
-
The `style`attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM `style`JavaScript property, is more efficient, and prevents XSS security holes. For example:
68
+
El atributo `style`acepta un objeto de Javascript con propiedades escritas en formato *camelCase*, en lugar de un *string* CSS. Esto es consistente con la propiedad DOM `style`en Javascript, es más eficiente y previene vulnerabilidades XSS. Por ejemplo:
68
69
69
70
```js
70
71
constdivStyle= {
@@ -77,66 +78,64 @@ function HelloWorldComponent() {
77
78
}
78
79
```
79
80
80
-
Note that styles are not autoprefixed. To support older browsers, you need to supply corresponding style properties:
81
+
Ten en cuenta que estos estilos no reciben automáticamente los prefijos de compatibilidad. Para ser compatible con navegadores antiguos, debes proveer las propiedades correspondientes:
81
82
82
83
```js
83
84
constdivStyle= {
84
-
WebkitTransition:'all', //note the capital 'W' here
85
-
msTransition:'all'// 'ms' is the only lowercase vendor prefix
85
+
WebkitTransition:'all', //nota la 'W' mayúscula aquí
86
+
msTransition:'all'// 'ms' es el único prefijo de proveedor de navegador en minúscula
86
87
};
87
88
88
89
functionComponentWithTransition() {
89
90
return<div style={divStyle}>This should work cross-browser</div>;
90
91
}
91
92
```
93
+
Las propiedades del objeto aceptado por `style` tienen formato camelCase para ser consistentes con la forma en que se accede a los estilos de los nodos DOM en JS (p.ej `node.style.backgroundImage`). Los prefijos de compatibilidad, [a excepción de `ms`](http://www.andismith.com/blog/2012/02/modernizr-prefixed/), deben iniciarse con letra mayúscula. Por esto `WebkitTransition` tiene una "W" mayúscula.
92
94
93
-
Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. `node.style.backgroundImage`). Vendor prefixes [other than `ms`](http://www.andismith.com/blog/2012/02/modernizr-prefixed/) should begin with a capital letter. This is why `WebkitTransition` has an uppercase "W".
94
-
95
-
React will automatically append a "px" suffix to certain numeric inline style properties. If you want to use units other than "px", specify the value as a string with the desired unit. For example:
95
+
React adjuntará automáticamente el sufijo "px" a ciertas propiedades numéricas. Si quieres usar unidades diferentes a "px", especifica el valor como un *string* con la unidad deseada. Por ejemplo:
96
96
97
97
```js
98
-
//Result style: '10px'
98
+
//Estilo resultante: '10px'
99
99
<div style={{ height:10 }}>
100
100
Hello World!
101
101
</div>
102
102
103
-
//Result style: '10%'
103
+
//Estilo resultante: '10%'
104
104
<div style={{ height:'10%' }}>
105
105
Hello World!
106
106
</div>
107
107
```
108
108
109
-
Not all style properties are converted to pixel strings though. Certain ones remain unitless (eg`zoom`, `order`, `flex`). A complete list of unitless properties can be seen [here](https://github.com/facebook/react/blob/4131af3e4bf52f3a003537ec95a1655147c81270/src/renderers/dom/shared/CSSProperty.js#L15-L59).
109
+
Sin embargo, no todas las propiedades numéricas del objeto `style` son convertidas a *strings* con píxeles. Ciertas propiedades se mantienen sin unidad (p.ej`zoom`, `order`, `flex`). Una lista completa de las propiedades sin unidad puede verse [aquí](https://github.com/facebook/react/blob/4131af3e4bf52f3a003537ec95a1655147c81270/src/renderers/dom/shared/CSSProperty.js#L15-L59).
110
110
111
111
### suppressContentEditableWarning
112
112
113
-
Normally, there is a warning when an element with children is also marked as `contentEditable`, because it won't work. This attribute suppresses that warning. Don't use this unless you are building a library like [Draft.js](https://facebook.github.io/draft-js/)that manages`contentEditable`manually.
113
+
Normalmente, hay una advertencia cuando un elemento con hijos también se marca como `contentEditable`, porque no funcionará. Este atributo suprime esa advertencia. No lo uses a menos que estés construyendo una biblioteca como [Draft.js](https://facebook.github.io/draft-js/)que administra`contentEditable`manualmente.
114
114
115
115
### suppressHydrationWarning
116
116
117
-
If you use server-side React rendering, normally there is a warning when the server and the client render different content. However, in some rare cases, it is very hard or impossible to guarantee an exact match. For example, timestamps are expected to differ on the server and on the client.
117
+
Si usas renderización de React del lado del servidor, normalmente hay una advertencia cuando el servidor y el cliente presentan contenido diferente. Sin embargo, en algunos casos raros, es muy difícil o imposible garantizar una coincidencia exacta. Por ejemplo, se espera que las marcas de tiempo difieran en el servidor y en el cliente.
118
118
119
-
If you set `suppressHydrationWarning`to`true`, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don't overuse it. You can read more about hydration in the [`ReactDOM.hydrate()` documentation](/docs/react-dom.html#hydrate).
119
+
Si estableces `suppressHydrationWarning`como`true`, React no te advertirá sobre los desajustes en los atributos y el contenido de ese elemento. Solo funciona a un nivel de profundidad y está diseñado para ser utilizado como una vía de escape. No lo uses en exceso. Puedes leer más sobre hidratación en la [documentación de `ReactDOM.hydrate()`](/docs/react-dom.html#hydrate).
120
120
121
121
### value
122
122
123
-
The `value`attribute is supported by `<input>` and `<textarea>` components. You can use it to set the value of the component. This is useful for building controlled components. `defaultValue`is the uncontrolled equivalent, which sets the value of the component when it is first mounted.
123
+
El atributo `value`es compatible con los componentes`<input>`y`<textarea>`. Puedes usarlo para establecer el valor del componente. Esto es útil para construir componentes controlados. `defaultValue`es el equivalente no controlado, que establece el valor del componente cuando se monta por primera vez.
124
124
125
-
## All Supported HTML Attributes
125
+
## Todos los atributos HTML admitidos
126
126
127
-
As of React 16, any standard [or custom](/blog/2017/09/08/dom-attributes-in-react-16.html) DOM attributes are fully supported.
127
+
A partir de React 16, se admite cualquier atributo de DOM estándar [o personalizado](/blog/2017/09/08/dom-attributes-in-react-16.html).
128
128
129
-
React has always provided a JavaScript-centric API to the DOM. Since React components often take both custom and DOM-related props, React uses the `camelCase`convention just like the DOM APIs:
129
+
React siempre ha proporcionado una API para el DOM centrada en JavaScript. Dado que los componentes de React a menudo reciben tanto props personalizados como props relacionados con el DOM, React utiliza la convención `camelCase`igual que las APIs del DOM:
130
130
131
131
```js
132
-
<div tabIndex="-1"/>//Just like node.tabIndex DOM API
133
-
<div className="Button"/>//Just like node.className DOM API
134
-
<input readOnly={true} />//Just like node.readOnly DOM API
132
+
<div tabIndex="-1"/>//Como la API del DOM node.tabIndex
133
+
<div className="Button"/>//Como la API del DOM node.className
134
+
<input readOnly={true} />//Como la API del DOM node.readOnly
135
135
```
136
+
Estos props funcionan de manera similar a sus atributos HTML correspondientes, con la excepción de los casos especiales documentados anteriormente.
136
137
137
-
These props work similarly to the corresponding HTML attributes, with the exception of the special cases documented above.
138
-
139
-
Some of the DOM attributes supported by React include:
138
+
Algunos de los atributos DOM admitidos por React son:
140
139
141
140
```
142
141
accept acceptCharset accessKey action allowFullScreen alt async autoComplete
0 commit comments