9

您好我想实现scrollview捕捉到中心 像下面gif链接水平滚动视图捕捉反应本土

Check This Gif

但未能如愿。以下是我的反应原生代码来实现这一点。

或者是否有任何方法滚动到滚动视图元素的特定索引像android?

任何帮助,将不胜感激。 在此先感谢

  <ScrollView 

            style={[styles.imgContainer,{backgroundColor:colorBg,paddingLeft:20}]} 
            automaticallyAdjustInsets={false} 

            horizontal={true} 
            pagingEnabled={true} 
            scrollEnabled={true} 
            decelerationRate={0} 
            snapToAlignment='center' 
            snapToInterval={DEVICE_WIDTH-100} 
            scrollEventThrottle={16} 
            onScroll={(event) => { 
            var contentOffsetX=event.nativeEvent.contentOffset.x; 
            var contentOffsetY=event.nativeEvent.contentOffset.y; 

            var cellWidth = (DEVICE_WIDTH-100).toFixed(2); 
            var cellHeight=(DEVICE_HEIGHT-200).toFixed(2); 

            var cellIndex = Math.floor(contentOffsetX/ cellWidth); 

            // Round to the next cell if the scrolling will stop over halfway to the next cell. 
            if ((contentOffsetX- (Math.floor(contentOffsetX/cellWidth) * cellWidth)) > cellWidth) { 
            cellIndex++; 
            } 

            // Adjust stopping point to exact beginning of cell. 
            contentOffsetX = cellIndex * cellWidth; 
            contentOffsetY= cellIndex * cellHeight; 

            event.nativeEvent.contentOffsetX=contentOffsetX; 
            event.nativeEvent.contentOffsetY=contentOffsetY; 

            // this.setState({contentOffsetX:contentOffsetX,contentOffsetY:contentOffsetY}); 



            console.log('cellIndex:'+cellIndex); 

            console.log("contentOffsetX:"+contentOffsetX); 
             // contentOffset={{x:this.state.contentOffsetX,y:0}} 



            }} 
            > 
            {rows} 

           </ScrollView> 

回答

1

有几种选择。这里有两个我已经尝试过,工作正常。我更喜欢第二个,因为它的文档说“像ListView,这可以渲染数百页没有性能问题”。

  1. react-native-page-swiper
  2. react-native-viewpager
+2

https://www.npmjs.com/package/react-native-snap-carousel – Gajus

7

你不需要,你可以做到这一点与滚动型其他库。所有你需要的是在你的组件中添加以下道具。

horizontal= {true} 
    decelerationRate={0} 
    snapToInterval={200} //your element width 
    snapToAlignment={"center"} 

检查这个零食关于如何实现更多的细节它 https://snack.expo.io/H1CnjIeDb

+0

用'ListView'过哪些作品更高性能,因为它拥有所有'ScrollView'的道具。 –

+0

如果我有一个X单位的标题和Y单位的边距,那么间隔是多少? – aprofromindia

+0

区间只关心宽度,可以使用维度库'const {width} = Dimensions.get('window')获得装置宽度;'然后只应用所有维度,包括边距和什么不到snapToInterval像这样' snapToInterval = {width - 60}' 查看上面的博览会了解更多详情 –