最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there an alternative for position: 'sticky in react-native? - Stack Overflow

programmeradmin1浏览0评论

I'm trying to make an element stay at the top of the screen at all times, vene when scrolling. I found out that position: 'sticky' does this for regular html. I was wondering if there was something I could add to my css to make the element stick to one place while scrolling using react-native.

I'm trying to make an element stay at the top of the screen at all times, vene when scrolling. I found out that position: 'sticky' does this for regular html. I was wondering if there was something I could add to my css to make the element stick to one place while scrolling using react-native.

Share Improve this question asked Nov 26, 2021 at 22:37 SourSour 312 silver badges7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

On ScrollView there is a prop called stickyHeaderIndices. Pass the index of the ponent that you want to be sticky in this prop. For example, if you want to sticky the header to be sticky from the below code, you have to just pass 1 in stickyHeaderIndices props like this :

import React from 'react';
import { View, ScrollView, StyleSheet, Text } from 'react-native';

const App = () => {
  return (
    <ScrollView stickyHeaderIndices={[1]}>
      <View>
        <Text style={styles.overline}>
          Overline
        </Text>
      </View>
      <View>
        <Text style={styles.header}>
          Header
        </Text>
      </View>
      {/* Your others ponent goes here */}
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  overline: {
    fontSize: 12,
    fontWeight: '100'
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold'
  },
  spacer: {
    height: 10,
  }
});

export default App;

This prop accepts the array, so you can also set multiple sticky ponents by passing the index of those all ponents.

I found that ScrollView's stickyHeaderIndices didn't work for my use-case, where I had an element that wasn't full-screen. (It stretched the element out to full screen; when I tried to wrap it in a View, it stopped being sticky.)

What worked for me was simply putting the element I wished to be sticky before the ScrollView, rather than inside it, and applying absolute positioning. A similar approach also worked for me for a sticky footer.


<MyComponent style={{position: absolute;}}/> // will be sticky to top
<ScrollView> 
    // scrolling ponents
</ScrollView>
<OtherComponent /> // functionally sticky to bottom; looks like content is scrolling behind it, even though the scrollview just stops before it.

发布评论

评论列表(0)

  1. 暂无评论