在实际的项目开发过程中,以数组为格式对组件进行渲染的情况是经常出现的,在React中,如果数组项item不为元素标签时,通常用arr.map(function (item,index) { return 组件或元素 })轮询数组并渲染。
当数组项为字符串时:
var Demo1 = React.createClass({ render:function(){ var names = ['Alice', 'Emily', 'Kate']; return ( <div> { names.map(function (name,index) { var theKey = "key"+index; return <div key={theKey}>Hello, {name}!</div> }) } </div> ); } }); ReactDOM.render(<Demo1 />,document.getElementById("example"));当数组项为标签元素时:
var Demo2 = React.createClass({ render:function(){ var arr = [ <h1 key="key1">Hello World</h1>, <h2 key="key2">Hello World</h2> ]; return ( <div>{arr}</div> ); } }); ReactDOM.render(<Demo2 />,document.getElementById("example"));当数组项为对象时:
var LiItem = React.createClass({ render: function() { return <li>{this.props.data.name}</li>; } }); var App = React.createClass({ render: function () { return ( <ul> { this.props.results.map(function(result,index){ return <LiItem key={result.id} data={result} />; }) } </ul> ); } }); var results = [ {id:'key1', name:'key1_data'}, {id:'key2', name:'key2_data'}, {id:'key3', name:'key3_data'} ]; ReactDOM.render( <App results={results} />, document.getElementById('example') );