react实现轮播图,以及实现绑定组件。
绑定组件:
//
创建一个变量, 与某个组件绑定
fl = React.createRef();
在html中创建ref={this.fl},
在函数中操作:this.fl.current.scrollToIndex({index: this.current})
具体看以下代码
// rnc
import React, {Component} from 'react';
import {Dimensions, FlatList, Image, Text, View} from 'react-native';
const {width, height} = Dimensions.get('screen');
const rpx = x => (width / 750) * x;
export default class App extends Component {
douyu = 'http://capi.douyucdn.cn/api/v1/live?limit=20&offset=0';
state = {data: []};
componentDidMount() {
fetch(this.douyu)
.then(res => res.json())
.then(res => {
console.log(res);
this.setState({data: res.data});
//请求结束时, 添加定时器
setInterval(() => {
// 每2.5秒, 让 FlatList 滚动到下一个
// console.log(this.fl); //debug模式可以看打印, 但是尽量不开. 会导致定时器bug
// 刷新时, 会有报错; 关闭应用 重新打开即可
// 超出限制: 当序号为最大值(长度-1) 则变为0 否则+1
this.current =
this.current == this.state.data.length - 1 ? 0 : this.current + 1;
this.fl.current.scrollToIndex({index: this.current});
}, 2500);
});
}
current = 0; //滚动操作的 当前页序号
//创建一个变量, 与某个组件绑定
fl = React.createRef();
render() {
return (
<View>
<FlatList
// ref属性 用于绑定 自身 和 某个变量
ref={this.fl}
data={this.state.data}
keyExtractor={(item, index) => index + ''}
renderItem={this._renderItem}
// 横向 和 多列是 互斥关系. 不能同时出现
// numColumns={2}
// horizontal:横向滚动
horizontal
// 按页滚动
pagingEnabled
// onScroll: 监听滚动操作的事件
onScroll={this._onScroll}
/>
</View>
);
}
_onScroll = event => {
// React触发的事件参数做过特殊处理: 同步虚拟事件.
// 要想看打印的值, 必须先调用: event.persist()
// event.persist();
// console.log(event);
// 通过滚动操作中 x 轴的位移, 除以屏幕宽度, 就可以知道移动了几个屏
const offset_x = event.nativeEvent.contentOffset.x;
// width: 屏幕宽
// round: 四舍五入的方式做处理
const current = Math.round(offset_x / width);
console.log(current);
// 滚动操作 实时更新当前页数
this.current = current;
};
_renderItem = ({item}) => {
const online =
item.online >= 1e4 ? (item.online / 1e4).toFixed(1) + '万' : item.online;
return (
<View style={{width}}>
<View style={{borderRadius: 5, overflow: 'hidden'}}>
<Image
source={{uri: item.room_src}}
style={{width: '100%', height: width * 0.55}}
/>
<Text
style={{
position: 'absolute',
right: 0,
color: 'white',
padding: 2,
backgroundColor: 'rgba(0,0,0,0.2)',
left: 0,
textAlign: 'right',
}}>
{online}
</Text>
<Text
style={{
position: 'absolute',
color: 'white',
bottom: 0,
padding: 4,
}}>
{item.nickname}
</Text>
</View>
<Text
style={{fontSize: rpx(30), margin: 2, color: 'gray'}}
numberOfLines={1}>
{item.room_name}
</Text>
</View>
);
};
}