UNPKG

@td-design/react-native-tabs

Version:

基于 @td-design/react-native 的 tabs 组件

73 lines (65 loc) 2.24 kB
import React, { useEffect, useRef } from 'react'; import { ScrollView, StyleSheet } from 'react-native'; import { useSafeState } from '@td-design/rn-hooks'; export default function ScrollBar(_ref) { let { height, page, children } = _ref; const [tabLayouts, setTabLayouts] = useSafeState([]); // 保存每个Tab的布局 const handleTabLayout = layouts => { setTabLayouts(layouts); }; // 保存ScrollView的宽度 const [contentWidth, setContentWidth] = useSafeState(0); const handleContentChange = width => { setContentWidth(width); }; // 保存滚动条的宽度 const [scrollBarWidth, setScrollBarWidth] = useSafeState(0); const handleScrollBarLayout = e => { setScrollBarWidth(e.nativeEvent.layout.width); }; const scrollViewRef = useRef(null); useEffect(() => { var _scrollViewRef$curren; if (tabLayouts.length - 1 < page || contentWidth === 0 || scrollBarWidth === 0) return; // 当前选中的Tab的布局 const tabLayout = tabLayouts[page]; // 当前选中的Tab的中心点 const tabCenter = tabLayout.x + tabLayout.width / 2 - scrollBarWidth / 2; // 计算ScrollView的最大可滚动距离[0, maxScrollX] const maxScrollX = contentWidth - scrollBarWidth; // 计算ScrollView应该滚动的x坐标位置,它必须在[0, maxScrollX]之间 const scrollX = Math.min(Math.max(0, tabCenter), maxScrollX); // 滚动ScrollView (_scrollViewRef$curren = scrollViewRef.current) === null || _scrollViewRef$curren === void 0 ? void 0 : _scrollViewRef$curren.scrollTo({ x: scrollX, animated: true }); }, [page, tabLayouts, contentWidth, scrollBarWidth]); return /*#__PURE__*/React.createElement(ScrollView, { ref: scrollViewRef, horizontal: true, bounces: false, showsHorizontalScrollIndicator: false, style: [styles.scrollbar, { height }], onContentSizeChange: handleContentChange, onLayout: handleScrollBarLayout, contentContainerStyle: { flexGrow: 1 } }, /*#__PURE__*/React.cloneElement(children, { onTabsLayout: handleTabLayout })); } const styles = StyleSheet.create({ scrollbar: { flexGrow: 0 } }); //# sourceMappingURL=ScrollBar.js.map