React equivalente para ng-repeat
Soy nuevo en Reaccionar.js. Estoy tratando de enlazar matrices de datos. Estoy buscando el equivalente de ng-repeat, pero no puedo encontrarlo dentro de la documentación.
Ej:
var data = ['red', 'green', 'blue']
Usando angular habría hecho algo como esto en mi html:
<div ng-repeat="i in data">{{i}}</div>
Me pregunto el marcado de React para hacer esto
5 answers
En React, simplemente escribes el JavaScript necesario (y potencialmente lo construyes en un control reutilizable como verás). Es muy prescriptivo y fácil de hacer una vez que aprendes los patrones básicos (y cómo difieren de AngularJS).
Por lo tanto, en la función render
, tendría que iterar a través de la lista. En el siguiente ejemplo, he usado map
, pero puedes usar otros iteradores según sea necesario.
var List = React.createClass({
render: function() {
return (<div>
{ this.props.data.map(function(item) {
return <div>{item}</div>
})
}
</div>);
}
});
var data = ['red', 'green', 'blue'];
React.render(<List data={ data } />, document.body);
Aquí está en uso.
Y, como puede ver, puede construir rápidamente un componente reutilizable que puede "repetir" a través de la lista.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-11 19:22:38
Debería ser:
{data.map(i => <div>{i}</div>)}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-11 19:10:14
Aquí hay un ejemplo usando ES6, y un componente sin estado.
El siguiente código muestra la creación de un menú haciendo un bucle a través de una lista de elementos de menú.
import React from 'react';
import Menu from 'material-ui/lib/menus/menu';
import MenuItem from 'material-ui/lib/menus/menu-item';
const menuItems = [
{route: '/questions', text: 'Questions'},
{route: '/jobs', text: 'Jobs'},
{route: '/tags', text: 'Tags'},
{route: '/users', text: 'Users'},
{route: '/badges', text: 'Badges'}
{route: '/questions/new', text: 'Ask Question'}
].map((item, index) => <MenuItem key={index} primaryText={item.text} value={item.route} />);
const Sidebar = ({history}) => (
<Menu
autoWidth={false}
onItemTouchTap={(e, child) => history.push(child.props.value)}
>
{menuItems}
</Menu>
);
export default Sidebar;
Básicamente lo que estamos haciendo es solo iteración javascript pura utilizando matriz .map .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-25 05:36:07
En tu función render dentro de un componente react puedes hacer esto:
var data = ['red', 'green', 'blue'];
var dataComponent = [];
data.forEach(function (dataValue) {
dataComponent.push(<div> {dataValue} </div>);
});
Y ahora puede devolver el componente de datos.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-11 19:14:44
Para realizar la misma tarea que ng-repeat en React, solo necesita pensar de forma nativa. Bajo el capó ng-repeat está usando un iterador nativo de Javascript. Puedes usar el mismo tipo de iterador nativo directamente en React. Por ejemplo, usaré Array.mapa:
var RepeatModule = React.createClass({
getInitialState: function() {
return { items: [] }
},
render: function() {
var listItems = this.props.items.map(function(item) {
return (
<li key={item.name}>
<a href={item.link}>{item.name}</a>
</li>
);
});
return (
<div>
<ul>
{listItems}
</ul>
</div>
);
}
});
Obtuve el ejemplo anterior de http://angulartoreact.com/ng-repeat-react-equivalent . El sitio tiene más ejemplos de React equivaents a las directivas Angulares.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-24 20:26:00