FloatingList 
提供为列表组件创建可组合子 API 的能力
¥Provides the ability to create composable children APIs for list components
import {FloatingList, useListItem} from '@floating-ui/react';这对于避免需要跟踪 useListNavigation 或 useTypeahead 的列表项索引很有用。
¥This is useful to prevent the need to keep track of a list item’s
index for useListNavigation or
useTypeahead.
当封装标签包围列表项时(例如分组),手动指定索引会带来问题。
¥Manually specifying an index poses problems when wrapper tags surround list items, such as with grouping.
可组合子 API 的示例如下所示,其中 <Select> 不接收数组 prop,而是接收子元素:
¥An example of a composable children API looks like the following,
where <Select> does not receive an array prop but rather
children:
<Select>
  <OptionGroup label="Fruits">
    <Option>Apple</Option>
    <Option>Strawberry</Option>
    <Option>Banana</Option>
  </OptionGroup>
  <OptionGroup label="Vegetables">
    <Option>Carrot</Option>
    <Option>Green Peas</Option>
    <Option>Cauliflower</Option>
  </OptionGroup>
</Select>示例
¥Examples
用法
¥Usage
FloatingList
该组件是一个上下文提供者,接收两个 props:
¥This component is a context provider that receives two props:
- 
elementsRef — useListNavigation()的listRef属性(元素数组)。¥elementsRef — useListNavigation()’slistRefprop (array of elements).
- 
labelsRef — useTypeahead()的listRef属性(字符串数组;可选)。¥labelsRef — useTypeahead()’slistRefprop (array of strings; optional).
const elementsRef = useRef([]);
const labelsRef = useRef([]);
 
const listNav = useListNavigation(context, {
  listRef: elementsRef,
});
const typeahead = useTypeahead(context, {
  listRef: labelsRef,
});
 
return (
  <FloatingList elementsRef={elementsRef} labelsRef={labelsRef}>
    {/* floating element with list item children */}
  </FloatingList>
);useListItem()
该 Hook 用于在 FloatingList 中注册列表项及其索引(DOM 位置)。它返回两个属性:
¥This Hook is used to register a list item and its index (DOM
position) in the FloatingList. It returns two properties:
ref 和 index。
¥ref and index.
function Option() {
  const {activeIndex} = useSelectContext();
  const {ref, index} = useListItem();
 
  const isActive = activeIndex === index;
 
  return <div ref={ref} tabIndex={isActive ? 0 : -1} />;
}Hook 可以选择接受 label 属性,该属性用于确定可以与 typeahead 匹配的字符串:
¥The Hook optionally accepts a label prop, which is used to
determine the string that can be matched with typeahead:
function Option({label}) {
  const {activeIndex} = useSelectContext();
  const {ref, index} = useListItem({
    label,
  });
 
  // ...
}对于禁用的项目,label 可以是 null,在预输入时将忽略该项目。
¥The label can be null for disabled items, which will be
ignored for typeahead.