## 第七篇動手寫組件
React-Native的核心思想就是組件化,相當于MVC的view,因此開發應用的最佳方式就是將功能組件化。
### 一、最簡單的方式
這里我們實現一個最簡單的組件,就是郵件的末尾署名的組件。組件意味著復用,意味著統一。現在有這樣一個需求,我們需要根據不同用戶發送郵件時,生成每個用戶的名片(即郵件末尾的署名)。
1、一般一開始的實現方式如下,直接將組件內容寫到功能需求的地方:
~~~
<View>
<View>..........這里是當前郵件組的其它功能</View>
<View>
<Text>框架研發部</Text>
<Text>www.ctrip.com</Text>
</View>
</View>
~~~
2、有一天,其它的部門的同事提出他們也需要在其他的地方,增加他們的郵件署名,那么你是否又會復制一份代碼呢,當然不是,我們可以組件化:
~~~
var Email = React.createClass({
render: function(){
return (
<View style={styles.container}>
<Text style={styles.text}>{this.props.name}</Text>
<Text style={styles.text}>{this.props.url}</Text>
</View>
);
}
});
~~~
3、整體的代碼如下:

### 二、循環一個文章列表
要實現的效果如下圖:

第一步改造我們的組件
~~~
var Article = React.createClass({
render: function(){
return (
<View style={styles.container}>
<Text style={[styles.text, styles.title]}>{this.props.title}</Text>
<Text style={styles.text}>{this.props.author}</Text>
<Text style={styles.text}>{this.props.time}</Text>
</View>
);
}
});
~~~
第二步定義數據model和循環
~~~
var App = React.createClass({
getInitialState: function(){
var data = [
{
title: "React-Native入門指南",
author: "vczero",
time: "2015-06-28"
},
{
title: "為什么世界不一樣",
author: "vczero",
time: "2015-06-8"
},
{
title: "你來,我就告訴你",
author: "vczero",
time: "2015-04-01"
}
];
return {
articles: data
};
},
render: function(){
return(
<ScrollView>
{this.state.articles.map(function(article){
return <Article title={article.title} author={article.author} time={article.time}/>
})}
</ScrollView>
);
}
});
~~~
整個代碼如下:
