(草稿)
先把代码放上来,再补充说明
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>React ListView</title> 5 <!-- 6 做一个列表控件,列表元素的模板可以设置,模仿ItemTemplate 7 --> 8 <script src="../build/react-with-addons.js" type="text/javascript"></script> 9 <script src="../build/JSXTransformer.js" type="text/javascript"></script> 10 <style type="text/css"> 11 .selected{ 12 color: red; 13 } 14 </style> 15 </head> 16 <body> 17 18 <script type="text/jsx"> 19 20 var TextItem = React.createClass({ 21 render:function(){ 22 var item = this.props.item; 23 return <p>this is {item}</p> 24 } 25 }); 26 27 var Template = React.createClass({ 28 render:function(){ 29 return React.createElement(this.props.type,this.props); 30 } 31 }); 32 33 var ListViewItem = React.createClass({ 34 render:function(){ 35 var item = this.props.item; 36 var cls = this.props.isSelected?'selected':''; 37 if(this.props.template){ /*有没有模板内容不同*/ 38 return <li className={cls} onClick={this.props.onClick}><Template type={this.props.template} item={item}></Template></li>; 39 }else{ 40 return <li className={cls} onClick={this.props.onClick}>{item}</li>; 41 } 42 } 43 }); 44 45 var ListView = React.createClass({ 46 getInitialState: function() { 47 return {selectedItem: ''}; 48 }, 49 onSelect:function(item){ 50 this.setState({selectedItem:item}); 51 console.log('selected item:' + item); 52 }, 53 render: function() { 54 var itemTemplate = this.props.itemTemplate?this.props.itemTemplate:''; 55 var selectedItem = this.state.selectedItem; 56 return ( 57 <ol> 58 { 59 this.props.items.map(function (item,i) { 60 var isSelected = (item ==selectedItem); 61 return <ListViewItem key={i} item={item} template={itemTemplate} isSelected={isSelected} onClick={this.onSelect.bind(this,item)}></ListViewItem> 62 },this) 63 } 64 </ol> 65 ); 66 } 67 }); 68 69 var items=['item1','item2','item3']; 70 React.render( 71 <ListView items={items} itemTemplate={TextItem}> 72 </ListView>, 73 document.body 74 ); 75 </script> 76 </body> 77 </html>
第一步理解这个例子