Dynamically changing number of columns in React Native Flat List

限于喜欢 提交于 2020-06-11 17:08:08

问题


I have a FlatList where I want to change the number of columns based on orientation. However, I get the red screen when I do this. As per the red screen error message, I'm not quite sure how I should be changing the key prop. Any help is appreciated.

      // dynamically changing number of columns
      const numCols = orientation === constants.PORTRAIT ? 3 : 8

      <FlatList
        keyExtractor={(_, i) => i}
        numColumns={numCols} // assigning the number of columns
        horizontal={false}
        renderItem={({ item }) => <ListItem imageUrl={item.url} />}
      />}


回答1:


From the documentation, looks like you should do something like this

key={(this.state.horizontal ? 'h' : 'v')}



回答2:


I did it using key

    numColumns = {this.state.columnCount}
    key={this.state.columnCount}



回答3:


Pass a changing value to the FlatList itself. It has nothing to do with the keyExtractor or the key attrbibute in renderItem methods:

<FlatList key={changingValue} .. /> 

should solve it.




回答4:


I think the message is very clear. You need to define different keys for portrait/landscape if you want to change the number of columns to force a fresh re-render. Try concatenating the numCols value to the index in your keyExtractor.




回答5:


horizontal={false}
numColumns={2}

Try this



来源:https://stackoverflow.com/questions/44291781/dynamically-changing-number-of-columns-in-react-native-flat-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!