Skip to main content

FlatList

用于渲染基本、扁平列表的高性能界面,支持最方便的功能:

¥A performant interface for rendering basic, flat lists, supporting the most handy features:

  • 完全跨平台。

    ¥Fully cross-platform.

  • 可选水平模式。

    ¥Optional horizontal mode.

  • 可配置的可见度回调。

    ¥Configurable viewability callbacks.

  • 标头支持。

    ¥Header support.

  • 页脚支持。

    ¥Footer support.

  • 分隔符支持。

    ¥Separator support.

  • 拉动刷新。

    ¥Pull to Refresh.

  • 滚动加载。

    ¥Scroll loading.

  • 滚动到索引支持。

    ¥ScrollToIndex support.

  • 多列支持。

    ¥Multiple column support.

如果你需要部分支持,请使用 <SectionList>

¥If you need section support, use <SectionList>.

示例

¥Example

要渲染多列,请使用 numColumns 属性。使用此方法而不是 flexWrap 布局可以防止与项目高度逻辑发生冲突。

¥To render multiple columns, use the numColumns prop. Using this approach instead of a flexWrap layout can prevent conflicts with the item height logic.

下面是更复杂、可选择的示例。

¥More complex, selectable example below.

  • 通过将 extraData={selectedId} 传递给 FlatList,我们确保 FlatList 本身会在状态更改时重新渲染。如果不设置此属性,FlatList 将不知道它需要重新渲染任何项目,因为它是 PureComponent 并且属性比较不会显示任何变化。

    ¥By passing extraData={selectedId} to FlatList we make sure FlatList itself will re-render when the state changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is a PureComponent and the prop comparison will not show any changes.

  • keyExtractor 告诉列表使用 id 作为反应键,而不是默认的 key 属性。

    ¥keyExtractor tells the list to use the ids for the react keys instead of the default key property.

这是 <VirtualizedList> 的便捷封装,因此继承了此处未明确列出的属性(以及 <ScrollView> 的属性),并附带以下注意事项:

¥This is a convenience wrapper around <VirtualizedList>, and thus inherits its props (as well as those of <ScrollView>) that aren't explicitly listed here, along with the following caveats:

  • 当内容滚动出渲染窗口时,不会保留内部状态。确保所有数据都在项目数据或外部存储(例如 Flux、Redux 或 Relay)中捕获。

    ¥Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.

  • 这是 PureComponent,这意味着如果 props 保持浅层相等,它将不会重新渲染。确保 renderItem 函数所依赖的所有内容都作为 prop(例如 extraData)传递,而更新后不是 ===,否则你的 UI 可能不会因更改而更新。这包括 data 属性和父组件状态。

    ¥This is a PureComponent which means that it will not re-render if props remain shallow-equal. Make sure that everything your renderItem function depends on is passed as a prop (e.g. extraData) that is not === after updates, otherwise your UI may not update on changes. This includes the data prop and parent component state.

  • 为了限制内存并实现平滑滚动,内容在屏幕外异步渲染。这意味着滚动速度可能快于填充速度,并暂时看到空白内容。这是一个可以调整以适应每个应用的需求的权衡,我们正在幕后努力改进它。

    ¥In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.

  • 默认情况下,列表会在每个项目上查找 key 属性并将其用作 React 键。或者,你可以提供自定义 keyExtractor 属性。

    ¥By default, the list looks for a key prop on each item and uses that for the React key. Alternatively, you can provide a custom keyExtractor prop.


参考

¥Reference

属性

¥Props

VirtualizedList 属性

¥VirtualizedList Props

继承 VirtualizedList 属性

¥Inherits VirtualizedList Props.


renderItem({
item: ItemT,
index: number,
separators: {
highlight: () => void;
unhighlight: () => void;
updateProps: (select: 'leading' | 'trailing', newProps: any) => void;
}
}): JSX.Element;

data 获取一个项目并将其渲染到列表中。

¥Takes an item from data and renders it into the list.

提供额外的元数据,如 index(如果需要)以及更通用的 separators.updateProps 函数,该函数可让你设置想要更改前导分隔符或尾随分隔符的渲染的任何属性,以防更常见的 highlightunhighlight(设置 highlighted: boolean prop) 不足以满足你的用例。

¥Provides additional metadata like index if you need it, as well as a more generic separators.updateProps function which let you set whatever props you want to change the rendering of either the leading separator or trailing separator in case the more common highlight and unhighlight (which set the highlighted: boolean prop) are insufficient for your use case.

类型
function
  • item(对象):正在渲染 data 中的项目。

    ¥item (Object): The item from data being rendered.

  • index(号码):data 数组中与此项对应的索引。

    ¥index (number): The index corresponding to this item in the data array.

  • separators(目的)

    ¥separators (Object)

    • highlight(功能)

      ¥highlight (Function)

    • unhighlight(功能)

      ¥unhighlight (Function)

    • updateProps(功能)

      ¥updateProps (Function)

      • select(枚举('leading','trailing'))

        ¥select (enum('leading', 'trailing'))

      • newProps(目的)

        ¥newProps (Object)

用法示例:

¥Example usage:

<FlatList
ItemSeparatorComponent={
Platform.OS !== 'android' &&
(({highlighted}) => (
<View
style={[style.separator, highlighted && {marginLeft: 0}]}
/>
))
}
data={[{title: 'Title Text', key: 'item1'}]}
renderItem={({item, index, separators}) => (
<TouchableHighlight
key={item.key}
onPress={() => this._onPress(item)}
onShowUnderlay={separators.highlight}
onHideUnderlay={separators.unhighlight}>
<View style={{backgroundColor: 'white'}}>
<Text>{item.title}</Text>
</View>
</TouchableHighlight>
)}
/>

要渲染的项目的数组(或类似数组的列表)。可以通过直接定位 VirtualizedList 来使用其他数据类型。

¥An array (or array-like list) of items to render. Other data types can be used by targeting VirtualizedList directly.

类型
类数组

ItemSeparatorComponent

在每个项目之间渲染,但不在顶部或底部。默认情况下,提供 highlightedleadingItem 属性。renderItem 提供了 separators.highlight/unhighlight,它将更新 highlighted 属性,但你也可以使用 separators.updateProps 添加自定义属性。可以是 React 组件(例如 SomeComponent),或 React 元素(例如 <SomeComponent />)。

¥Rendered in between each item, but not at the top or bottom. By default, highlighted and leadingItem props are provided. renderItem provides separators.highlight/unhighlight which will update the highlighted prop, but you can also add custom props with separators.updateProps. Can be a React Component (e.g. SomeComponent), or a React element (e.g. <SomeComponent />).

类型
组件、函数、元素

ListEmptyComponent

当列表为空时渲染。可以是 React 组件(例如 SomeComponent),或 React 元素(例如 <SomeComponent />)。

¥Rendered when the list is empty. Can be a React Component (e.g. SomeComponent), or a React element (e.g. <SomeComponent />).

类型
组件、元素

ListFooterComponent

渲染在所有项目的底部。可以是 React 组件(例如 SomeComponent),或 React 元素(例如 <SomeComponent />)。

¥Rendered at the bottom of all the items. Can be a React Component (e.g. SomeComponent), or a React element (e.g. <SomeComponent />).

类型
组件、元素

ListFooterComponentStyle

ListFooterComponent 内部视图的样式。

¥Styling for internal View for ListFooterComponent.

类型
View 样式

ListHeaderComponent

渲染在所有项目的顶部。可以是 React 组件(例如 SomeComponent),或 React 元素(例如 <SomeComponent />)。

¥Rendered at the top of all the items. Can be a React Component (e.g. SomeComponent), or a React element (e.g. <SomeComponent />).

类型
组件、元素

ListHeaderComponentStyle

ListHeaderComponent 内部视图的样式。

¥Styling for internal View for ListHeaderComponent.

类型
View 样式

columnWrapperStyle

numColumns > 1.0 时生成的多项目行的可选自定义样式。

¥Optional custom style for multi-item rows generated when numColumns > 1.

类型
View 样式

extraData

用于告诉列表重新渲染的标记属性(因为它实现了 PureComponent)。如果你的任何 renderItem、页眉、页脚等功能依赖于 data 属性之外的任何内容,请将其粘贴在这里并以不变的方式对待它。

¥A marker property for telling the list to re-render (since it implements PureComponent). If any of your renderItem, Header, Footer, etc. functions depend on anything outside of the data prop, stick it here and treat it immutably.

类型
any

getItemLayout

(data, index) => {length: number, offset: number, index: number}

getItemLayout 是一项可选优化,如果你提前知道项目的尺寸(高度或宽度),则可以跳过动态内容的测量。如果你有固定尺寸的物品,getItemLayout 会很有效,例如:

¥getItemLayout is an optional optimization that allows skipping the measurement of dynamic content if you know the size (height or width) of items ahead of time. getItemLayout is efficient if you have fixed size items, for example:

  getItemLayout={(data, index) => (
{length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
)}

对于包含数百个项目的列表,添加 getItemLayout 可以极大地提升性能。如果指定 ItemSeparatorComponent,请记住在偏移计算中包括分隔符长度(高度或宽度)。

¥Adding getItemLayout can be a great performance boost for lists of several hundred items. Remember to include separator length (height or width) in your offset calculation if you specify ItemSeparatorComponent.

类型
function

horizontal

如果为 true,则水平渲染彼此相邻的项目,而不是垂直堆叠。

¥If true, renders items next to each other horizontally instead of stacked vertically.

类型
boolean

initialNumToRender

初始批次中要渲染的项目数。这应该足以填满屏幕,但不能太多。请注意,这些项目永远不会作为窗口渲染的一部分被卸载,以提高滚动到顶部操作的感知性能。

¥How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.

类型默认
number10

initialScrollIndex

不要从顶部的第一项开始,而是从 initialScrollIndex 开始。这将禁用 "滚动到顶部" 优化,该优化使前 initialNumToRender 项始终渲染,并立即渲染从此初始索引开始的项。需要实现 getItemLayout

¥Instead of starting at the top with the first item, start at initialScrollIndex. This disables the "scroll to top" optimization that keeps the first initialNumToRender items always rendered and immediately renders the items starting at this initial index. Requires getItemLayout to be implemented.

类型
number

inverted

反转滚动方向。使用 -1 的比例变换。

¥Reverses the direction of scroll. Uses scale transforms of -1.

类型
boolean

keyExtractor

(item: ItemT, index: number) => string;

用于提取指定索引处给定项目的唯一键。键用于缓存并作为跟踪项目重新排序的反应键。默认提取器检查 item.key,然后检查 item.id,然后回退到使用索引,就像 React 那样。

¥Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item.key, then item.id, and then falls back to using the index, like React does.

类型
function

numColumns

多列只能用 horizontal={false} 渲染,并且会像 flexWrap 布局一样呈锯齿形。物品的高度应相同 - 不支持砌体布局。

¥Multiple columns can only be rendered with horizontal={false} and will zig-zag like a flexWrap layout. Items should all be the same height - masonry layouts are not supported.

类型
number

onRefresh

() => void;

如果提供,将为 "拉动刷新" 功能添加标准 RefreshControl。确保正确设置 refreshing 属性。

¥If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the refreshing prop correctly.

类型
function

onViewableItemsChanged

当行的可见性发生变化时调用,如 viewabilityConfig 属性所定义。

¥Called when the viewability of rows changes, as defined by the viewabilityConfig prop.

类型
(callback: {changed: ViewToken[], viewableItems: ViewToken[]} => void;

progressViewOffset

当加载指示器需要偏移才能正确显示时,请设置此项。

¥Set this when offset is needed for the loading indicator to show correctly.

类型
number

refreshing

在等待刷新的新数据时将其设置为 true。

¥Set this true while waiting for new data from a refresh.

类型
boolean

removeClippedSubviews

这可以提高大型列表的滚动性能。在 Android 上,默认值为 true

¥This may improve scroll performance for large lists. On Android the default value is true.

注意:在某些情况下可能会出现错误(缺少内容) - 使用风险由你自行承担。

¥Note: May have bugs (missing content) in some circumstances - use at your own risk.

类型
boolean

viewabilityConfig

有关流类型和更多文档,请参阅 ViewabilityHelper.js

¥See ViewabilityHelper.js for flow type and further documentation.

类型
可见度配置

viewabilityConfig 采用类型 ViewabilityConfig 具有以下属性的对象

¥viewabilityConfig takes a type ViewabilityConfig an object with following properties

属性类型
minimumViewTimenumber
viewAreaCoveragePercentThresholdnumber
itemVisiblePercentThresholdnumber
waitForInteractionboolean

至少需要 viewAreaCoveragePercentThresholditemVisiblePercentThreshold 之一。这需要在 constructor 中完成,以避免出现以下错误 (ref):

¥At least one of the viewAreaCoveragePercentThreshold or itemVisiblePercentThreshold is required. This needs to be done in the constructor to avoid following error (ref):

  Error: Changing viewabilityConfig on the fly is not supported
constructor (props) {
super(props)

this.viewabilityConfig = {
waitForInteraction: true,
viewAreaCoveragePercentThreshold: 95
}
}
<FlatList
viewabilityConfig={this.viewabilityConfig}
...

minimumViewTime

在触发可视性回调之前,项目必须物理可见的最短时间(以毫秒为单位)。较高的数字意味着不停地滚动内容不会将内容标记为可见。

¥Minimum amount of time (in milliseconds) that an item must be physically viewable before the viewability callback will be fired. A high number means that scrolling through content without stopping will not mark the content as viewable.

viewAreaCoveragePercentThreshold

部分被遮挡的项目必须覆盖的视口百分比才能算作 "viewable", 0-100。完全可见的项目始终被视为可见。值 0 表示视口中的单个像素使项目可见,值 100 表示项目必须完全可见或覆盖整个视口才算可视。

¥Percent of viewport that must be covered for a partially occluded item to count as "viewable", 0-100. Fully visible items are always considered viewable. A value of 0 means that a single pixel in the viewport makes the item viewable, and a value of 100 means that an item must be either entirely visible or cover the entire viewport to count as viewable.

itemVisiblePercentThreshold

viewAreaCoveragePercentThreshold 类似,但考虑的是可见项目的百分比,而不是其覆盖的可视区域的比例。

¥Similar to viewAreaCoveragePercentThreshold, but considers the percent of the item that is visible, rather than the fraction of the viewable area it covers.

waitForInteraction

在用户滚动或渲染后调用 recordInteraction 之前,没有任何内容被视为可见。

¥Nothing is considered viewable until the user scrolls or recordInteraction is called after render.


viewabilityConfigCallbackPairs

ViewabilityConfig/onViewableItemsChanged 对列表。当满足对应的 ViewabilityConfig 的条件时,将调用特定的 onViewableItemsChanged。有关流类型和更多文档,请参阅 ViewabilityHelper.js

¥List of ViewabilityConfig/onViewableItemsChanged pairs. A specific onViewableItemsChanged will be called when its corresponding ViewabilityConfig's conditions are met. See ViewabilityHelper.js for flow type and further documentation.

类型
ViewabilityConfigCallbackPair 数组

方法

¥Methods

flashScrollIndicators()

flashScrollIndicators();

暂时显示滚动指示器。

¥Displays the scroll indicators momentarily.


getNativeScrollRef()

getNativeScrollRef(): React.ElementRef<typeof ScrollViewComponent>;

提供对底层滚动组件的引用

¥Provides a reference to the underlying scroll component


getScrollResponder()

getScrollResponder(): ScrollResponderMixin;

提供底层滚动响应程序的句柄。

¥Provides a handle to the underlying scroll responder.


getScrollableNode()

getScrollableNode(): any;

提供底层滚动节点的句柄。

¥Provides a handle to the underlying scroll node.

scrollToEnd()

scrollToEnd(params?: {animated?: boolean});

滚动到内容末尾。如果没有 getItemLayout 属性,可能会很卡顿。

¥Scrolls to the end of the content. May be janky without getItemLayout prop.

参数:

¥Parameters:

名称类型
paramsobject

有效的 params 键为:

¥Valid params keys are:

  • 'animated'(布尔值) - 列表是否应该在滚动时播放动画。默认为 true

    ¥'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to true.


scrollToIndex()

scrollToIndex: (params: {
index: number;
animated?: boolean;
viewOffset?: number;
viewPosition?: number;
});

滚动到指定索引处的项目,使其位于可视区域中,viewPosition 0 将其放置在顶部,1 将其放置在底部,0.5 将其放置在中间居中。

¥Scrolls to the item at the specified index such that it is positioned in the viewable area such that viewPosition 0 places it at the top, 1 at the bottom, and 0.5 centered in the middle.

注意:如果不指定 getItemLayout 属性,则无法滚动到渲染窗口之外的位置。

¥Note: Cannot scroll to locations outside the render window without specifying the getItemLayout prop.

参数:

¥Parameters:

名称类型
参数
必填
object

有效的 params 键为:

¥Valid params keys are:

  • 'animated'(布尔值) - 列表是否应该在滚动时播放动画。默认为 true

    ¥'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to true.

  • 'index'(号码) - 要滚动到的索引。必需的。

    ¥'index' (number) - The index to scroll to. Required.

  • 'viewOffset'(号码) - 偏移最终目标位置的固定数量的像素。

    ¥'viewOffset' (number) - A fixed number of pixels to offset the final target position.

  • 'viewPosition'(号码) - 值 0 会将索引指定的项目放在顶部,1 放在底部,0.5 放在中间居中。

    ¥'viewPosition' (number) - A value of 0 places the item specified by index at the top, 1 at the bottom, and 0.5 centered in the middle.


scrollToItem()

scrollToItem(params: {
animated?: ?boolean,
item: Item,
viewPosition?: number,
});

需要线性扫描数据 - 如果可能,请使用 scrollToIndex

¥Requires linear scan through data - use scrollToIndex instead if possible.

注意:如果不指定 getItemLayout 属性,则无法滚动到渲染窗口之外的位置。

¥Note: Cannot scroll to locations outside the render window without specifying the getItemLayout prop.

参数:

¥Parameters:

名称类型
参数
必填
object

有效的 params 键为:

¥Valid params keys are:

  • 'animated'(布尔值) - 列表是否应该在滚动时播放动画。默认为 true

    ¥'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to true.

  • 'item'(对象) - 要滚动到的项目。必需的。

    ¥'item' (object) - The item to scroll to. Required.

  • 'viewPosition'(号码)

    ¥'viewPosition' (number)


scrollToOffset()

scrollToOffset(params: {
offset: number;
animated?: boolean;
});

滚动到列表中的特定内容像素偏移。

¥Scroll to a specific content pixel offset in the list.

参数:

¥Parameters:

名称类型
参数
必填
object

有效的 params 键为:

¥Valid params keys are:

  • 'offset'(号码) - 滚动到的偏移量。如果 horizontal 为真,则偏移量为 x 值,在任何其他情况下,偏移量为 y 值。必需的。

    ¥'offset' (number) - The offset to scroll to. In case of horizontal being true, the offset is the x-value, in any other case the offset is the y-value. Required.

  • 'animated'(布尔值) - 列表是否应该在滚动时播放动画。默认为 true

    ¥'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to true.