示例
实用示例,实时演示。
挑一个示例全屏打开,运行效果和源码并排呈现。
挑一个示例全屏打开,运行效果和源码并排呈现。
只要元素还留在数组里,list() 就会保住它的那一行:重排、插入、重命名,输入框和焦点都不会丢。再打开一个开关,让每次更新都克隆对象,就能看到替换对象引用要付出什么代价。
Type into a row, then reorder or insert: the row keeps its input and its focus, and the mount count only grows by what was inserted. Flip the switch and every change rebuilds every row.
import 'nuclo' interface Person { id: number; name: string } let people: Person[] = [ { id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }, { id: 3, name: 'Linus' }, ] let nextId = 4 let clone = false let mounts = 0 // Counts every row built, refreshing only the "stats" scope. const mounted = () => on('mount', () => { mounts++ queueMicrotask(() => update('stats')) }) const row = { style: { display: 'flex', flexWrap: 'wrap', gap: '6px' } } // list() matches rows to items by identity (===). A row whose item is // still in the array is kept: its DOM, its input's text, its focus. // Reordering moves the same nodes. Only new items build new rows. // With the switch on, every update() hands list() fresh copies of the // objects. They are not the same items any more, so every row is rebuilt. const items = () => (clone ? people.map((p) => ({ ...p })) : people) function Row(p: Person) { return div( mounted(), { style: { display: 'flex', alignItems: 'center', gap: '8px' } }, small(`#${p.id}`), input({ placeholder: `Type here: ${p.name}`, 'aria-label': `Note for ${p.name}` }), span(() => p.name), // dynamic: a rename shows without a rebuild button('✕', { 'aria-label': `Remove ${p.name}`, onClick: () => { people = people.filter((x) => x.id !== p.id); update() }, }), ) } export const App = () => div( div(scope('stats'), span('rows ', b(() => String(people.length))), span('mounts ', b(() => String(mounts)))), list(items, Row), div( row, button('Reverse', { onClick: () => { people = [...people].reverse(); update() }, }), button('Sort by name', { onClick: () => { people = [...people].sort((a, b) => a.name.localeCompare(b.name)); update() }, }), button('Insert at top', { onClick: () => { people = [{ id: nextId, name: `Person ${nextId++}` }, ...people] update() }, }), // Mutate the item in place: the row is kept and the text updates. button('Rename first', { onClick: () => { people[0].name += '!'; update() }, }), ), // The pitfall: new objects every update are new items to list(), // so every row is torn down and rebuilt, and typed text is lost. label( input({ type: 'checkbox' }, { checked: () => clone }, { onChange: () => { clone = !clone; update() } }), 'Clone the objects on every update (breaks identity)', ), p('Type into a row, then reorder or insert: the row keeps its input and its focus, and the mount count only grows by what was inserted. Flip the switch and every change rebuilds every row.'), )