首页 > 其他 > 详细

横向tab计算滚动位置

时间:2019-12-06 11:23:57      阅读:55      评论:0      收藏:0      [点我收藏+]

React Native横向滚动计算

import {View, Text, ScrollView, TouchableOpacity} from 'react-native';
import {_container, _inner, _item, _text} from './index.style';

const offsetX = 50; // tab默认偏移量

export default class FixedTab extends QComponent {
    static reduxPlugin = {
        mapStateToProps: state => state
    }

    constructor(props) {
        super(props);
        this.scrollX = 0; // scroller的动态x偏移量
        this.scrollWidth = 0; // scroller容器的宽度
        this.contentWidth = 0; // scroller内部元素的宽度
        this.itemLayout = {}; // scroller初始化每项的x偏移量
    }

    onScroll(e) {
        this.scrollX = e.nativeEvent.contentOffset.x;
    }

    onLayout(e) {
        this.scrollWidth = e.nativeEvent.layout.width;
    }

    onContentLayout(e) {
        this.contentWidth = e.nativeEvent.layout.width;
    }

    onItemLayout(e, index) {
        this.itemLayout[index] = e.nativeEvent.layout.x;
    }

    changeType(index) {
        // 滚动逻辑
        const itemOffsetX = this.itemLayout[index] - this.scrollX;
        if(itemOffsetX > offsetX) { // 右侧超出固定偏移量
            if(this.itemLayout[index] + this.scrollWidth - offsetX < this.contentWidth) {
                this.scroller.scrollTo({x: this.itemLayout[index] - offsetX});
            } else {
                this.scroller.scrollTo({x: this.contentWidth - this.scrollWidth});
            }
        } else {
            if(this.itemLayout[index] > offsetX) { // 默认当前元素偏移量大于固定偏移量
                this.scroller.scrollTo({x: this.itemLayout[index] - offsetX});
            } else {
                this.scroller.scrollTo({x: 0});
            }
        }
    }

    render() {
        return <ScrollView
            ref={node => this.scroller = node}
            style={_container}
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            onLayout={e => this.onLayout(e)}
            onScroll={e => this.onScroll(e)}
            scrollEventThrottle={16}
        >
            <View style={_inner} onLayout={e => this.onContentLayout(e)}>
            {list.map((item, i) =>
                <View key={i} onLayout={e => this.onItemLayout(e, i)}>
                    <TouchableOpacity style={_item} onPress={() => this.changeType(i)}>
                        <Text style={_text}>{item.name}</Text>
                    </TouchableOpacity>
                </View>
            )}
            </View>
        </ScrollView>;
    }
}

横向tab计算滚动位置

原文:https://www.cnblogs.com/ljwk/p/11994156.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!