React Native开发经验集

React-Native SectionList布局介绍

2017-07-26  本文已影响0人  煎包小混沌

先敬上炫酷的效果图:


9102DA01-DF73-4141-8767-286C3EFD1F91.png

前面学习了FlatListhttp://www.jianshu.com/p/c464a2688663
但是FlatList并不支持section的分组功能。

这里介绍SectionList完美的实现了分组功能,和FlatList一样,性能更优

主要属性:

renderItem:渲染每一个item,很重要哦
sections:提供数据源,很重要哦
ListHeaderComponent:列表-表头,可以不用
ListFooterComponent:列表-表尾巴,可以不用
renderSectionHeader:每一个分组section,分组必须要哈
keyExtractor:每个renderItem的key,如果相同则不渲染这个renderItem,很重要,很重要,很重要,千万不要重复

创建一个SectionList

<SectionList
  renderItem={({item}) => <ListItem title={item.title} />}
  renderSectionHeader={({section}) => <H1 title={section.key} />}
  sections={[ // 不同section渲染相同类型的子组件
    {data: [...], key: ...},
    {data: [...], key: ...},
    {data: [...], key: ...},
  ]}
/>

<SectionList
  sections={[ // 不同section渲染不同类型的子组件
    {data: [...], key: ..., renderItem: ...},
    {data: [...], key: ..., renderItem: ...},
    {data: [...], key: ..., renderItem: ...},
  ]}
/>

引用其他作者的话:

sections 就是我们的数据源,每一个data 就是我们要用的item, renderItem就是你要显示的子控件哦。如果你每个组都复用一个子组件那就按照例一的结构, 如果你想要不同的组返回不同样式的子组件那就按照例二的结构返回不同的renderItem即可。这里提个醒, key一定要有, 不同的section 要设置不同的key才会渲染相应的section, 如果你key值都相同, 那可能会出现只显示一组数据的情况哦~

这里的解释,是摘抄别人的,他的简书链接,本文也是参考这里的http://www.jianshu.com/p/6302c4d48b97

以下分别介绍SectionList的属性赋值,如果不想看,可以拉到最后,查看完整代码
1.为ListHeaderComponent创建一个view,作为表头

_listHeaderComponent =()=> {
        return(
            <View style={{backgroundColor: '#aaaaff'}}>
                <Text>
                    我是listHeader
                </Text>
            </View>
        )
    };

2.为ListFooterComponent创建一个view,作为表尾巴

_listFooterComponent =()=> {
         return(
             <View style={{backgroundColor: '#aaaaff'}}>
                 <Text>
                     我是listFooter
                 </Text>
             </View>
         )
    };

3.为renderSectionHeader创建一个view,作为每个section

//参数需要{}修饰,告诉section是个对象
    _renderSectionHeader = ({section}) => {
        return(
            <View style={{flex: 1, height: 25, backgroundColor: '#11ffff', justifyContent: 'center'}}>
                <Text style={styles.sectionHeader}>{section.key}</Text>
            </View>
        )
    };

4.为renderItem创建一个view,作为每个item

//先创建一个Row对象,代表每个item界面
class Row extends Component {
    _rowClick =()=>{
        let rowNum = this.props.data.row;
        alert(rowNum);
    };
    render(){
        return(
            <TouchableOpacity style={styles.row} onPress={this._rowClick}>
                <View style={{flex:1, alignItems: 'center', justifyContent: 'center', backgroundColor: this._backColor()}}>
                    <Text>
                        {this.props.data.value}
                    </Text>
                </View>
            </TouchableOpacity>
        )
    }
//随机取色的方法
    _backColor =()=> {
        let r=Math.floor(Math.random()*256);
        let g=Math.floor(Math.random()*256);
        let b=Math.floor(Math.random()*256);
        let s = "rgb("+r+','+g+','+b+")";
        console.log('_backColor'+s);
        return s;//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
    }
}
//使用用Row对象来创建item
//参数需要{}修饰,告诉item是个对象,其实这里的item是个数组包含对象,使用map来遍历数组
    _renderItem =({item})=> {
        return (
        <View style={styles.list}>
            {
                item.map((val, i)=>{
                    return <Row key={i} data={val}/>
                })
            }
        </View>
        )
    };

4.设置keyExtractor的值,确保此值不重复

_extraUniqueKey =(item)=> {
        return "index"+item;
    };

5.为SectionList添加数据源sections
//rowData是一个包含对象的数组

sections={
                             this.state.rowData
                         }>

上面就是为了给SectionList的每个属性附上东东,接下来就是创建一个SectionList

直接上完整代码吧:
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
    SectionList,
    Text,
    Dimensions,
    TouchableOpacity
} from 'react-native';

let windowsSize = {
    width: Dimensions.get('window').width,
    height: Dimensions.get("window").height
};
class Row extends Component {
    _rowClick =()=>{
        let rowNum = this.props.data.row;
        alert(rowNum);
    };
    render(){
        return(
            <TouchableOpacity style={styles.row} onPress={this._rowClick}>
                <View style={{flex:1, alignItems: 'center', justifyContent: 'center', backgroundColor: this._backColor()}}>
                    <Text>
                        {this.props.data.value}
                    </Text>
                </View>
            </TouchableOpacity>
        )
    }
    _backColor =()=> {
        let r=Math.floor(Math.random()*256);
        let g=Math.floor(Math.random()*256);
        let b=Math.floor(Math.random()*256);
        let s = "rgb("+r+','+g+','+b+")";
        console.log('_backColor'+s);
        return s;//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
    }
}
export default class SectionView extends React.PureComponent{
    constructor(props){
        super(props);
        let data1 =  Array.from(new Array(5)).map((val, i)=>({
            value: '数据1='+i,
            row: i,
        }));
        let data2 =  Array.from(new Array(8)).map((val, i)=>({
            value: '数据2='+i,
            row: i,
        }));
        let data3 =  Array.from(new Array(11)).map((val, i)=>({
            value: '数据3='+i,
            row: i,
        }));
        //这里面的data属性后面跟数组,是为了在布局renderItem的时候可以传入的参数item是数组,而不是data1这个对象
        this.state = {
            rowData: [
                {key: 's1', data: [data1]},
                {key: 's2', data: [data2]},
                {key: 's3', data: [data3]}
                ]
        }

    }
    _listHeaderComponent =()=> {
        return(
            <View style={{backgroundColor: '#aaaaff'}}>
                <Text>
                    我是listHeader
                </Text>
            </View>
        )
    };
    _listFooterComponent =()=> {
         return(
             <View style={{backgroundColor: '#aaaaff'}}>
                 <Text>
                     我是listFooter
                 </Text>
             </View>
         )
    };
    //参数需要{}修饰,告诉是个对象
    _renderSectionHeader = ({section}) => {
        console.log('_renderSectionHeader' + section.key);
        return(
            <View style={{flex: 1, height: 25, backgroundColor: '#11ffff', justifyContent: 'center'}}>
                <Text style={styles.sectionHeader}>{section.key}</Text>
            </View>
        )
    };
    //参数需要{}修饰,告诉是个对象
    _renderItem =({item})=> {
        console.log('_renderItem' + item[0]);
        return (
        <View style={styles.list}>
            {
                item.map((val, i)=>{
                    return <Row key={i} data={val}/>
                })
            }
        </View>
        )
    };
    _extraUniqueKey =(item)=> {
        return "index"+item;
    };
    render(){
        return(
            <SectionList style={{flex: 1, backgroundColor: '#aaffaa', marginTop: 20}}
                         renderItem={this._renderItem}
                         ListFooterComponent={this._listFooterComponent}
                         ListHeaderComponent={this._listHeaderComponent}
                         renderSectionHeader={this._renderSectionHeader}
                         showsVerticalScrollIndicator={false}
                         keyExtractor = {this._extraUniqueKey}
                         sections={
                             this.state.rowData
                         }>

            </SectionList>
        )
    }
}
const styles = StyleSheet.create({
    list:{
        flexDirection: 'row', //这里的属性很重要,可以学习下flex布局
        flexWrap: 'wrap',
        alignItems: 'flex-start',
        backgroundColor: '#FFFFFF'
    },
    row:{
        backgroundColor: '#FFFFFF',
        justifyContent: 'center',
        // alignItems: 'center',
        width: windowsSize.width/4,
        height: windowsSize.width/4,
    },
    sectionHeader: {
        marginLeft: 10,
        fontSize: 12,
        color: '#787878'
    },
});
AppRegistry.registerComponent('SectionView', ()=>SectionView);
上一篇下一篇

猜你喜欢

热点阅读