[英]Centering view in scrollView carousel react native list of horizontal buttons - javascript
我已经从 react native docs 中尝试了很多属性,在 google 上进行了一些搜索,尤其是在 stackOverflow 上,但它们似乎都没有同时在 android 和 ios 两个平台上工作我不知道在这种情况下使用哪一个。 我在 ScrollView 中有一个按钮列表 20 我希望视图最初位于中心的按钮上。
常量按钮 = [...Array(21).keys()]
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
>
{buttons.map(button=> <TouchableOpacity key={button}>button</TouchableOpacity>)}
</ScrollView>
我希望按钮编号 10 位于屏幕中央,因为感谢初始视图帮助。
在我看来,更好和最小的解决方案是:
// simple array that has numbers from 0 till 20
const buttons = [...Array(21).keys()];
const [scrollView, setScrollView] = useState(null);
const scrollToIndex = (contentSize) => {
// getting desired index of button or you can simply do e.g. (const index = 2)
// for this example you can pass index = 10 or 9 to be centered perfectly or contentSize / 2
const index = options.reduce((acc, option, idx) => (option === 'desired-button-to-be-shown' ? (acc = idx) : acc));
// setting view to be centered on that index
scrollView.scrollTo({ x: (contentSize / options.length) * (index - 1) });
};
// this is your ScrollView Carousel / Slider
<ScrollView
// saving SrcollView reference in state
ref={(scrollViewRef) => setScrollView(scrollViewRef)}
horizontal
// getting the width of the whole ScrollView (all your content e.g. images / buttons)
onContentSizeChange={(contentSize) => scrollToIndex(contentSize)}
showsHorizontalScrollIndicator={false}>
{buttons.map((button) => (
<TouchableOpacity key={button}>button</TouchableOpacity>
))}
</ScrollView>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.