React Native - SectionList numColumns support

2019-02-22 02:55发布

问题:

FlatList has numColumns support. How to set numColumns with SectionList?

Github issue: SectionList renderItem multi item support #13192

回答1:

Here is my solution to numColumns for SectionList. If you have better let me know please.

class Example extends Component {
  static propTypes = {
    numColumns: PropTypes.number
  };

  static defaultProps = {
    numColumns: 2
  };

  _renderSection = data => <Section {...data} />;

  _renderItem = ({ section, index }) => {
    const { numColumns } = this.props;

    if (index % numColumns !== 0) return null;

    const items = [];

    for (let i = index; i < index + numColumns; i++) {
      if (i >= section.data.length) {
        break;
      }

      items.push(<Item item={section.data[i]} />);
    }

    return (
      <View
        style={{
          flexDirection: "row",
          justifyContent: "space-between"
        }}
      >
        {items}
      </View>
    );
  };

  render() {
    return (
      <SectionList
        sections={dumyData}
        style={styles.container}
        renderItem={this._renderItem}
        renderSectionHeader={this._renderSection}
      />
    );
  }
}


回答2:

It is possible to use FlatList with numColumns prop as the renderItem of SectionList.

const data = [ //Notice [[...]] instead of [...] as in the RN docs
    {data: [[...]], title: ...},
    {data: [[...]], title: ...},
    {data: [[...]], title: ...},
]

render () {
    return (
        <SectionList
            renderItem={this._renderSectionListItem}
            renderSectionHeader={this._renderSectionHeader}
            sections={data}
        />
    )
}

renderSectionListItem = ({item}) => {
    return (
        <FlatList
            data={item}
            numColumns={3}
            renderItem={this.renderItem}
        />
    )
}


回答3:

Digging this issue up, I came with a solution similar to Pir Shukarullah Shah 's.

I'm using FlatList instead of my regular item, taking into account only the first item in <SectionList/>'s renderItem method.

 _renderList = ({ section, index }) => {
    if (index !== 0) return null;

    return (
      <FlatList numColumns={columns}
        columnWrapperStyle={styles.container}
        data={section.data}
        renderItem={this._renderItem}
        keyExtractor={keyExtractor}
      />
    )
  }



...
      <SectionList
        renderItem={this._renderList}
        renderSectionHeader={this._renderSectionHeader}
        sections={itemList}
        keyExtractor={keyExtractor}
      />