How to Get ListView Section Header to Stick

后端 未结 2 1466
礼貌的吻别
礼貌的吻别 2021-01-30 15:17

I have buttons displayed on the top of the screen (used react-native-scrollable-tab-view). Underneath the buttons, I have ListView with section hea

2条回答
  •  太阳男子
    2021-01-30 15:49

    ListView Headers don't stick, you'll need to use renderSectionHeader and cloneWithRowsAndSections instead of cloneWithRows to do this.

    From the React Native documentation on ListView

    renderSectionHeader function 
    
    (sectionData, sectionID) => renderable
    
    If provided, a sticky header is rendered for this section. The sticky behavior means that it will scroll with the content at the top of the section until it reaches the top of the screen, at which point it will stick to the top until it is pushed off the screen by the next section header.
    

    I tackled this same issue today. Here's how I handled it. First, in getInitialState:

    getInitialState: function() {
    
      return {
        dataBlob: {},
        dataSource: new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2,
        sectionHeaderHasChanged: (s1, s2) => s1 !== s2
        }),
      }
    },
    

    Then, during my API call that gets data back, I add that response data to my dataBlob object. The key that stores it is considered the sectionId for ListView.DataSource. In this case, that sectionId is going to be the date of the posts I retrieve:

      getAllPosts: function() {
    
        api.getAllPosts()
          .then((responseData) => {
            var tempDataBlob = this.state.dataBlob;
            var date = new Date(responseData.posts[0].day).toDateString();
            tempDataBlob[date] = responseData.posts;
            this.setState({
              dataBlob: tempDataBlob
            });
            ;
          }).then(() => {
            this.setState({
              dataSource: this.state.dataSource.cloneWithRowsAndSections(this.state.dataBlob),
              loaded: true
            })
          })
          .done();
      },
    

    cloneWithRowsAndSections accepts a dataBlob (in my case, an object) as its first argument, and optional arguments of sectionIDs and rowIDs.

    Here's how renderListView looks:

      renderListView: function() {
        return (
           {this.getAllPosts(this.state.currentDay)}}
            onEndReachedThreshold={40}
            style={styles.postsListView} />
          )
      },
    

    And here's how renderSectionHeader looks:

      renderSectionHeader: function(sectionData, sectionID) {
        return (
          
            {sectionID}
          
          )
      },
    

    Here's how it looks in the end: imgur

提交回复
热议问题