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

I'm trying to make an element stay at the top of the screen at all times, vene when scrolling. I f

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745283230a4620404.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信