簡體   English   中英

scrollView 輪播中的居中視圖反應水平按鈕的本機列表 - javascript

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM