(草稿)
先把代码放上来,再补充说明
<!DOCTYPE html>
<html>
<head>
<title>React ListView</title>
<!--
做一个列表控件,列表元素的模板可以设置,模仿ItemTemplate
-->
<script src="../build/react-with-addons.js" type="text/javascript"></script>
<script src="../build/JSXTransformer.js" type="text/javascript"></script>
<style type="text/css">
.selected{
color: red;
}
</style>
</head>
<body> <script type="text/jsx"> var TextItem = React.createClass({
render:function(){
var item = this.props.item;
return <p>this is {item}</p>
}
}); var Template = React.createClass({
render:function(){
return React.createElement(this.props.type,this.props);
}
}); var ListViewItem = React.createClass({
render:function(){
var item = this.props.item;
var cls = this.props.isSelected?'selected':'';
if(this.props.template){ /*有没有模板内容不同*/
return <li className={cls} onClick={this.props.onClick}><Template type={this.props.template} item={item}></Template></li>;
}else{
return <li className={cls} onClick={this.props.onClick}>{item}</li>;
}
}
}); var ListView = React.createClass({
getInitialState: function() {
return {selectedItem: ''};
},
onSelect:function(item){
this.setState({selectedItem:item});
console.log('selected item:' + item);
},
render: function() {
var itemTemplate = this.props.itemTemplate?this.props.itemTemplate:'';
var selectedItem = this.state.selectedItem;
return (
<ol>
{
this.props.items.map(function (item,i) {
var isSelected = (item ==selectedItem);
return <ListViewItem key={i} item={item} template={itemTemplate} isSelected={isSelected} onClick={this.onSelect.bind(this,item)}></ListViewItem>
},this)
}
</ol>
);
}
}); var items=['item1','item2','item3'];
React.render(
<ListView items={items} itemTemplate={TextItem}>
</ListView>,
document.body
);
</script>
</body>
</html>
第一步理解这个例子