Horizontal scrollview snapping react native

前端 未结 4 1976
臣服心动
臣服心动 2021-01-31 09:19

Hi I am trying to achieve scrollview snap to center like below gif link

Check This Gif

But unable to do so. Following is my react nat

相关标签:
4条回答
  • 2021-01-31 09:54

    Use the pagingEnabled property in ScrollView.

    const screenHeight = Dimensions.get('window').height;
    
    class Screen extends Component {
      constructor(props) {
        super(props);
      }
    
      render() {
        return (
          <ScrollView pagingEnabled>
            <Page1 style={{height: screenHeight}} />
            <Page2 style={{height: screenHeight}} />
          </ScrollView>
        );
      }
    }
    
    0 讨论(0)
  • 2021-01-31 10:02

    You don't need other libraries you can do that with ScrollView. All you need is to add the following props in your component.

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

    Check this snack for more details on how to implement it https://snack.expo.io/H1CnjIeDb

    0 讨论(0)
  • 2021-01-31 10:03

    There are several options. Here are two that I've tried and work fine. I prefer the second one because as its doc says "like ListView, this can render hundreds of pages without performance issue".

    1. react-native-page-swiper
    2. react-native-viewpager
    0 讨论(0)
  • 2021-01-31 10:07

    If you don't want to use snapToInterval because of the misalignment for long lists you can use snapToOffsets which is more precise.

    for example:

    const { width } = Dimensions.get('window');
    this.IMAGE_WIDTH = width * (1 / 2.5)
    this.image_margin = 5
    this.nishhar = width - ((this.IMAGE_WIDTH + this.image_margin) * 2 + this.image_margin * 2)
    
    dataNum = [1, 2, 3, 4, 5, 6]
    
    return (<FlatList
                data={dataNum}
                renderItem={item => {
                    return (
                        <View style={{
                            backgroundColor: item.index % 2 == 0 ? 'red' : 'blue',
                            width: this.IMAGE_WIDTH,
                            height: this.IMAGE_WIDTH,
                            marginLeft: this.image_margin,
                            marginRight: this.image_margin,
                        }}>
                        </View>)
                }}
                keyExtractor={this.keyGenerator}
                horizontal={true}
                snapToAlignment={"start"}
                snapToOffsets={[...Array(dataNum.length)].map((x, i) => (i * (this.IMAGE_WIDTH + 2 * this.image_margin) - (this.nishhar * 0.5)))}
                decelerationRate={"fast"}
                pagingEnabled
            />)
    
    

    or you can also checkout this example: https://snack.expo.io/SyWXFqDAB

    0 讨论(0)
提交回复
热议问题