首页 > 解决方案 > React Native:列表的条件道具

问题描述

我想知道是否有一种方法可以根据条件为列表组件设置一组属性。

render() {
  return (
    <SectionList
      ref={(ref) => {this.listRef = ref}}
      style={styles.listContainer}
      sections={this.props.listData}
      fetchData={this.props.fetchData}
      keyExtractor={this.keyExtractor}
      renderSectionHeader={this.renderSectionHeader}
      renderItem={this.renderItem}
      ItemSeparatorComponent={this.separator}
      keyboardDismissMode='on-drag'
      initialNumToRender={6}
      stickySectionHeadersEnabled={false}
      // ListFooterComponent={this.renderFooter}
      // onEndReachedThreshold={0.5}
      // onEndReached={() => {
      //   this.props.fetchMoreData()}}
    />
  )
}

我想要ListFooterComponentonEndReachedThreshold并且onEndReached只有在设置时才this.props.fetchMoreData设置。我是否需要在渲染函数的顶部放置一个 if 语句,或者是否可以创建一个单独的道具来对这 3 个进行分组并使用扩展运算符根据条件将其放回 SectionList 中。我不太确定该怎么做。

标签: react-nativereact-native-sectionlist

解决方案


我结束了以下

  render() {
    optional = {}
    if (this.props.fetchMoreData) {
      optional.onEndReachedThreshold = 0.5
      optional.onEndReached = () => {
        this.props.fetchMoreData()}
      optional.ListFooterComponent = this.renderFooter
    }
    return (
      <SectionList
        ref={(ref) => {this.listRef = ref}}
        style={styles.listContainer}
        sections={this.props.listData}
        fetchData={this.props.fetchData}
        keyExtractor={this.keyExtractor}
        renderSectionHeader={this.renderSectionHeader}
        renderItem={this.renderItem}
        ItemSeparatorComponent={this.separator}
        keyboardDismissMode='on-drag'
        initialNumToRender={6}
        stickySectionHeadersEnabled={false}
        {...optional}
      />
    )

我想我最初绊倒了optional.ListFooterComponent。它对我来说看起来很奇怪,所以我认为它一定是错的;)


推荐阅读