react native之组织组件

这些组件包括<TabView>,<NavigatorView>和<ListView>,他们实现了手机端最常用的交互和导航。你会发现这些组件在实际的项目中会非常有用。

原生的<Listview>组件使用起来会很平滑和顺畅,如果你想在ListView里渲染大量的数据,你必须让视图足够简单,这样才能减少卡顿、

React Native的<ListView>组件需要两个属性:dataSource和renderRow.dataSource。

基本用法演示在SimpleList.js文件里,我们开始为我们的<SimleList>组件新增一个数据源,A ListView.DataSource需要实现rowHasChanged方法。下面是一个简单列子:

var ds=new ListView.DataSource(rowHasChanged:(r1,r2)=>r1!==r2);

为了在数据源中获取到实际的内容,我们使用cloneWithRows.在getInitialState方法中返回数据源:

getInitialState:function(){

var ds=new ListView.DataSource(rowHasChanged:(r1,r2)=>r1!==r2);
return{
  dataSource:ds.cloneWithRows(['标题1','标题2','标题3','标题4','标题5'])
};
}

另外需要的一个属性是renderRow,它需要一个函数返回使用JSX表示的数据的形式。如:

_renderRow:fuction(rowData){

return <Text style={styles.row}>{rowData}</Text>;

}

现在我们把他们都整合起来看起来像这样:

<ListView

dataSource={this.state.dataSource}

renderRow={this._renderRow}

/>

一、使用ListView

这里我们将创建一个APP来显示纽约时报销量列表,并且可以让我们浏览每本书的内容。

首先,我们先将数据源初始化为空,如下:

getInitialState:function(){

var ds=new ListView.DataSource(rowHasChanged:(r1,r2)=>r1!==r2);
return{
  dataSource:ds.cloneWithRows([])
};
}

然后,新增一个获取数据的方法并且一旦我们获得了数据就立即更新数据源。

_refreshData:function(){

var endpoint="http://api.nytimes.com/svc/books/v3/lists/hardcover-fiction?respone-format=json&api-key="+API_KEY;

fetch(endpoint)

.then((respone)=>respone.json())

.then((rjson)=>{

this.setState({

dataSource:this.state.dataSource.cloneWithRows(rjson.results.books)

});

});

}

纽约时报的API返回每本书都有三个属性分别是:coverURL,author,tittle.我们更新<ListView>的渲染函数将返回基于这三个属性的组件。

对于_renderRow,对于<BookItem>我们仅仅传递相关数据,如下:

_renderRow:function(rowData){

  return <BookItem coverURL={rowData.book_image}

                             title={rowData.title}

                              author={rowData.author}/>

},

我们还需要一个页脚页眉组件,来展示程序的功能。注意<ListView>,页脚和页眉不是粘的,他们与列表的其他内容一起滚动。如果你不希望这样,可以这样:

在BookListV2.js新增个方法来渲染页眉和页脚元素

_renderHeader:function(){

return (

  <View style={styles.sectionDivider}>

  <Text style={styles.headingText}>

    我是页眉

</Text>

  </View>);


},

_renderFooter:function(){

<View style={styles.sectionDivider}>

  <Text style={styles.headingText}>

    我是页脚

</Text>

  </View>);

},

这个应用包含2个文件:BookListV2.js和BookItem.js.