0.43之后 RN添加了Flatlist组件,作为ListView的增强版,FlatList有着很强的性能上的优势,而且使用起来也更简单。
这里着重介绍一下以下东西:
1. 添加头部组件,
2. 添加尾部组件,
3. 添加间隔组件,
4. 列表为空显示的组件,
5. flatlist的滚动方法。
最基础的:
<FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
最好是给data数据每一个item都添加一个key,不然会有黄色的警告。
我们这里不讲太过基础的东西,主要写一下它的滚动事件,以及添加头部尾部间隔组件等等。
首先是添加间隔组件:
<FlatList ItemSeparatorComponent={this.sepa} ref="_flatlist" horizontal={true} data={data} renderItem={({item}) => <Text style={{height: 50, width: 50}}>{item.title}</Text> } />
使用ItemSeparatorComponent的方法,然后里面调用我们自己的方法,也可以直接调用外部组件:
sepa() { return (<View style={{width:1,backgroundColor:'red'}}></View>) }
由于我的FlatList是横向的,所以我加了个竖向的线来分隔,
使Flatlist变横向的方法:
horizontal={true}默认为false,是竖向的。
下面上图:
FlatList添加头和尾同添加分隔组件的方法是一样的,属性分别是:
ListFooterComponent : ReactClass<any> 尾部组件
ListHeaderComponent : ReactClass<any> 头部组件
它们的高度(宽度)取决于Flatlist的方向 ,默认是和Item一样的,如果你有需要的话也可以自己写一个其他的高度。
它还有一个重要的方法,当列表为空时渲染的组件:
ListEmptyComponent :列表为空时渲染该组件。可以是React Component, 也可以是一个render函数, 或者渲染好的element。
<FlatList data={this.state.dataSource} renderItem={({item}) => { return <View style={{alignItems: 'center'}}><Text>{item}</Text></View> }} ListEmptyComponent={this.emptyComponent} ItemSeparatorComponent={this.separatorComponent} ListFooterComponent={() => this.headerorfooterComponent(2)} ListHeaderComponent={() => this.headerorfooterComponent(1)} extraData={this.state} onRefresh={() => this.refreshFlat()} refreshing={this.state.isRefreshing} />
refreshFlat() { this.setState({ dataSource: [] }) } headerorfooterComponent(x) { let i = x === 1 ? '我是头部' : '我是尾部------'; return ( this.state.dataSource.length !== 0 ? <View style={{alignItems: 'center', backgroundColor: 'green'}}> <Text>{i}</Text> </View> : null ) } separatorComponent() { return ( <View style={{backgroundColor: "green", height: 1}}> </View> ) } emptyComponent() { return (<View style={{ backgroundColor: 'red', flex: 1, height: 500, alignItems: 'center', justifyContent: 'center' }}> <Text>list为空</Text> </View>) }
this.state.dataSource.length !== 0 ? <View style={{alignItems: 'center', backgroundColor: 'green'}}> <Text>{i}</Text> </View> : null如果列表为空的话,头部和尾部都为null。
scrollToIndexparams: {animated?: ?boolean, index: number, viewPosition?: number}:滚动到指定的位置
scrollToOffset(params: {animated?: ?boolean, offset: number}):滚动到指定的偏移的位置。
官方文档上还有个方法 scrollToItem ,英文是Requires linear scan through data - use scrollToIndex instead if possible. 前半句我没懂,但是后面说的是:如果可以的话,用scrollToIndex 来代替它,所以不做介绍了~
//this.refs._flatlist.scrollToEnd(); //滚动到末尾,如果不设置getItemLayout属性的话,可能会比较卡 this.refs._flatlist.scrollToIndex({viewPosition: 0, index: 18}); //viewPosition 0位于顶部,1位于底部,0.5位于中间。 //this.refs._flatlist.scrollToOffset({animated: true, offset: 200}); //滚动到指定的偏移的位置
以上是3个方法,第一个和第三个就不多说了,一目了然,说下第二个scrollToIndex
第一个参数viewPosition是设置要显示的item的位置的,0是顶部,1是底部,0.5是中间,下面放图来演示一下:
不用多解释吧~