For
列表渲染组件,高效地渲染动态列表。
Props
ts
interface ForProps<T> extends ListLifecycleHook {
each: readonly T[]
children: (item: T, index: Ref<number>) => RenderChild
key?: keyof T | ((item: T) => any)
}| 属性 | 类型 | 说明 |
|---|---|---|
each | readonly T[] | 要遍历的数组 |
children | (item: T, index: Ref<number>) => RenderChild | 渲染函数 |
key | keyof T | ((item: T) => any) | 可选的 key 指定 |
ListLifecycleHook
列表生命周期钩子,用于实现列表项的过渡动画。
| 属性 | 类型 | 说明 |
|---|---|---|
onLeave | (view: View, done: () => void) => void | 列表项离开动画 |
onEnter | (view: View) => void | 列表项进入动画 |
onBeforeUpdate | (children: IterableIterator<View>) => void | 更新前回调 |
onAfterUpdate | (children: IterableIterator<View>) => void | 更新后回调 |
更新模型与开发模式警告
陈旧引用检测警告新增于 4.1.0 版本
children 只在行创建时执行一次,key 决定行的身份:同 key 的行被复用(保留 DOM 与行内状态),行内容通过行内信号表达式响应「原地修改」更新。
开发模式下,若检测到同 key 的数据项被替换为新对象引用且内容发生变化(行内容不会自动更新),For 会输出聚合警告,提示以下任一姿势:
- 原地修改该行数据(推荐,触发元素级精确更新)
- 使用
syncList同步全量新数据 - 将可变内容纳入 key(内容变化即重建该行)
- 替换数组时保持未变化项的对象引用稳定
生产构建中该检测被编译期消除,无运行时开销。
示例
基本用法:
tsx
import { For, ref } from 'vitarx'
function App() {
const items = ref(['a', 'b', 'c'])
return (
<For
each={items}
children={(item, index) => (
<div key={item}>
{index}: {item}
</div>
)}
/>
)
}指定 key:
tsx
<For each={users} key="id" children={(user) => <div>{user.name}</div>} />参考:For 详解