新建 AutoScrollView.js
import React, {Component} from 'react';
import {View,Text,ScrollView} from 'react-native'
class AutoScrollView extends Component {
static defaultProps = {
data:[],
delayTime:2000, //默认两秒
backgroundColor:'#eee', //默认颜色
height:160, //滚动视图的默认高度
scrollHeight:50, //每次滚动的高度
borderRadius:10, //滚动视图的默认圆角
startLength:3, //默认长度>3时开始滚动
};
constructor(props) {
super(props);
this.state = {
runIndex:0,
data:this.props.data,
}
}
async componentWillReceiveProps(nextProps, nextContext) {
// console.log('重新接收数据')
await this.setState({
data:nextProps.data
})
this.runScroll()
}
componentDidMount() {
this.runScroll()
}
/**滚动**/
runScroll() {
let runIndex = this.state.runIndex //开始滚动的下标
let list = this.state.data // 数据
let {delayTime,scrollHeight,startLength} = this.props
let that = this
this.timer2&&clearInterval(this.timer2)
this.timer2 = setInterval(function () {
// LOG("====>>>>> timer2")
if (runIndex < list.length - (startLength+1) ) {
runIndex++
let scroll_y = runIndex * scrollHeight
that.scrollview.scrollTo({x: 0, y: scroll_y, animated: true,})
} else {
runIndex = 0
that.scrollview.scrollTo({x: 0, y: 0, animated: false,})
}
that.setState({
runIndex: runIndex
})
}, delayTime)
}
componentWillUnmount() {
console.log('卸载了自动滚动')
this.timer2 &&clearInterval(this.timer2)
}
render() {
let {backgroundColor,height,borderRadius} = this.props
return (
<ScrollView showsVerticalScrollIndicator={false}
ref={(ref) => this.scrollview = ref} style={{
height: height,
borderRadius: borderRadius,
backgroundColor: backgroundColor
}}>
{
this.props.children?
this.props.children
:
this.state.data.map((item,id)=>{
return(
<View key={id} style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between',height:50,borderBottomWidth:1,borderColor:'#F0F0FD'}}>
<Text>{id}</Text>
</View>
)
})
}
</ScrollView>
);
}
}
export default AutoScrollView;
使用
import AutoScrollView from "../common/AutoScrollView";
constructor(props) {
super(props);
// 初始状态
this.state = {
got_list: [1,2,3,4,5],
runIndex: 0
};
}
<AutoScrollView
delayTime={2000}
backgroundColor={'#fff'}
height={160}
startLength={3} //长度大于多少时开始滚动,当长度小于这个值时不滚动,也不能,默认为大于3开始滚动
data={this.state.got_list}
scrollHeight={50} //每次滚动的高度、最好是和子视图每一项的高度一样,这样就是每次滚动一个
borderRadius={0}
>
{
this.state.got_list.map((item,id)=>{
return(
<View key={id} style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between',height:50,borderBottomWidth:1,borderColor:'#F0F0FD'}}>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}>
<View style={{width:20,height:20,borderRadius:999,backgroundColor:'green'}}/>
<Text style={{marginLeft:10,fontSize:11}}>好友名称{id}</Text>
</View>
<Text style={{color:'#017AFF',fontFamily:'KaiTi',fontSize:11}}>记录显示 - 已报名</Text>
</View>
)
})
}
</AutoScrollView>
网友评论