嗨,我正在尝试实现 scrollview
如下所示对齐中心 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>
原文由 Srinivas Guni 发布,翻译遵循 CC BY-SA 4.0 许可协议
您不需要其他库,您可以使用 ScrollView 做到这一点。您只需要在组件中添加以下道具。
查看此小吃以获取有关如何实施它的更多详细信息 https://snack.expo.io/H1CnjIeDb