美文网首页React Native
React Native之组件ListView

React Native之组件ListView

作者: 代码森林中的一只猫 | 来源:发表于2017-11-22 12:41 被阅读0次

React Native的组件ListView类似于iOS中的UITableView和UICollectionView,也就是说React Native的组件ListView既可以实现UITableView也可以实现UICollectionView。

一、ListView的使用方法

最简单的例子:

constructor(props) {
super(props);
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(['row 1', 'row 2']),
};
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData}</Text>}
/>
);
}

二、ListView常用的属性

ScrollView 相关属性样式全部继承

dataSource ListViewDataSource 设置ListView的数据源

initialListSize number
设置ListView组件刚刚加载的时候渲染的列表行数,用这个属性确定首屏或者首页加载的数量,而不是花大量的时间渲染加载很多页面数据,提高性能。

onEndReachedThreshold number
当偏移量达到设置的临界值调用onEndReached

pageSize number 每一次事件的循环渲染的行数

removeClippedSubviews bool
该属性用于提供大数据列表的滚动性能。该使用的时候需要给每一行(row)的布局添加over:'hidden'样式。该属性默认是开启状态。

三、ListView常用的方法

onChangeVisibleRows function
(visibleRows,changedRows)=>void。
当可见的行发生变化的时候回调该方法。

onEndReached function
当所有的数据项行被渲染之后,并且列表往下进行滚动。一直滚动到距离底部onEndReachedThredshold设置的值进行回调该方法。原生的滚动事件进行传递(通过参数的形式)。

renderFooter function 方法 ()=>renderable
在每次渲染过程中头和尾总会重新进行渲染。如果发现该重新绘制的性能开销比较大的时候,可以使用StaticContainer容器或者其他合适的组件
renderHeader function 方法
在每一次渲染过程中Footer(尾)该会一直在列表的底部,header(头)该会一直在列表的头部,用法同上。

renderRow function (rowData,sectionID,rowID,highlightRow)=>renderable
该方法有四个参数,其中分别为数据源中一条数据,分组的ID,行的ID,以及标记是否是高亮选中的状态信息。

renderScrollComponent function 方法 (props)=>renderable
该方法可以返回一个可以滚动的组件。默认该会返回一个ScrollView

renderSectionHeader function (sectionData,sectionID)=>renderable
如果设置了该方法,这样会为每一个section渲染一个粘性的header视图。该视图粘性的效果是当刚刚被渲染开始的时候,该会处于对应的内容的顶部,然后开始滑动的时候,该会跑到屏幕的顶端。直到滑动到下一个section的header(头)视图,然后被替代为止。

renderSeparator function (sectionID,rowID,adjacentRowHighlighted)=>renderable
如果设置该方法,会在被每一行的下面渲染一个组件作为分隔。除了每一个section分组的头部视图前面的最后一行。

scrollRenderAheadDistance number
进行设置当该行进入屏幕多少像素以内之后就开始渲染该行。

demo1

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView,
Image,
PixelRatio,
TouchableOpacity
} from 'react-native';

// 引入本地的数据
const wineArr = require('./localData/Wine.json');
export default class extends Component {
// 构造
constructor(props) {
super(props);

// 1.创建数据源
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});

// 初始状态
this.state = {
dataSource: ds.cloneWithRows([''])
};
}

render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow}
/>
);
}

componentDidMount() {
this.setState({
dataSource:this.state.dataSource.cloneWithRows(wineArr)
})
}


_renderRow(rowData, sectionID, rowID){
return(
<TouchableOpacity
style={styles.cellViewStyle}
onPress={()=>alert('点击了第' + sectionID + '组中的第' + rowID + '行')}
>
{/*左边*/}
<Image source={{uri: rowData.image}} style={styles.cellImgStyle}/>
{/*右边*/}
<View style={styles.rightViewStyle}>
<Text
style={styles.mainTitleStyle}
numberOfLines={2}
>
{rowData.name}
</Text>
<Text style={styles.subTitleStyle}>¥{rowData.money}.00</Text>
</View>
</TouchableOpacity>
)
}
}

const styles = StyleSheet.create({
cellViewStyle:{
borderBottomWidth: 1 / PixelRatio.get(),
borderBottomColor:'#ccc',

/*主轴的方向*/
flexDirection:'row',
padding:10
},

cellImgStyle:{
width: 90,
height: 60,
resizeMode:'contain'
},

rightViewStyle:{
flex:1,
// backgroundColor:'red',
justifyContent:'space-between'
},

mainTitleStyle:{
fontSize: 15,
color:'red'
},

subTitleStyle:{
color:'#999'
}
});

demo2 collectionView

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView,
    Image
} from 'react-native';

// 1.引入本地的数据
const shareData = require('./localData/shareData.json').data;

export default class  extends Component {
  // 构造
    constructor(props) {
      super(props);
      // 初始状态
      this.state = {
         dataSource: new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2})
      };
    }

  render() {
    return (
        <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderRow}
            contentContainerStyle={styles.contentContainerStyle}
        />
    );
  }

  componentDidMount() {
      this.setState({
          dataSource: this.state.dataSource.cloneWithRows(shareData)
      })
  }

  _renderRow(rowData){
    // console.log(rowData);
    // debugger;
    return(
         <View style={styles.cellViewStyle}>
             <Image source={{uri: rowData.icon}} style={{width:80, height:80, resizeMode:'contain'}}/>
             <Text>{rowData.title}</Text>
         </View>
      )
  }
}

const styles = StyleSheet.create({
    contentContainerStyle:{
        flexDirection:'row',
        flexWrap:'wrap',
        justifyContent:'space-around'
    },

    cellViewStyle: {
        width:100,
        height:100,
        justifyContent:'center',
        alignItems:'center'
    }
});

demo3 headerview

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView,
    Image
} from 'react-native';

// 导入本地的数据
var dataObj = require('./LocalData/Car.json');

export default class AListViewDemo extends Component {
  // 构造
    constructor(props) {
      super(props);

      // 1. 获取组的数据
      var getSectionData = (dataBlob, sectionID)=>{
          return dataBlob[sectionID];
      };

      // 2. 获取行的数据
      var getRowData = (dataBlob, sectionID, rowID)=>{
          return dataBlob[sectionID + ':' + rowID];
      };


      // 初始状态
      this.state = {
          dataSource: new ListView.DataSource({
              getSectionData: getSectionData,
              getRowData: getRowData,
              rowHasChanged: (r1, r2) => r1 !== r2,
              sectionHeaderHasChanged:(s1, s2) => s1 !== s2
          })
      };
    }

  render() {
    return (
        <ListView
            dataSource={this.state.dataSource}
            renderSectionHeader={this._renderSectionHeader}
            renderRow={this._renderRow}
        />
    );
  }

  componentDidMount() {
       // 1. 获取数据数组
       const dataArr = dataObj.data;

       var dataBlob = {}, sectionIDs = [], rowIDs = [], cars = [];

       // 2. 遍历
       for(var i=0; i<dataArr.length; i++){
          // 2.1 设置组的内容
          dataBlob[i] = dataArr[i].title;
          // 2.2 设置组号
          sectionIDs.push(i);

          rowIDs[i] = [];

          // 2.3 取出每一组中行的内容
          cars = dataArr[i].cars;
          for(var j=0; j<cars.length; j++){
              // 2.3.1 取出行号
              rowIDs[i].push(j);
              // 2.3.2 取出行的内容放入dataBlob
              dataBlob[i + ':' + j] = cars[j];
          }
       }

       // 3. 更新状态
       this.setState({
           dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs)
       });

       // console.log(dataBlob, sectionIDs, rowIDs);
  }

  _renderSectionHeader(sectionData){
      return (
         <View style={{backgroundColor:'#ccc'}}>
            <Text>{sectionData}</Text>
         </View>
      )
  }

  _renderRow(rowData){
      return(
          <View style={styles.cellStyle}>
             <Image source={{uri: rowData.icon}} style={styles.imgStyle}/>
             <Text>{rowData.name}</Text>
          </View>
      )
  }
}

const styles = StyleSheet.create({

  cellStyle:{
      flexDirection:'row',
      borderBottomColor:'#ccc',
      borderBottomWidth:1,
      padding:10
  },

  imgStyle:{
     width: 90,
     height:90,
     marginRight:10
  }
});

相关文章

网友评论

    本文标题: React Native之组件ListView

    本文链接:https://www.haomeiwen.com/subject/dcynvxtx.html