예제
실용적인 예제와 라이브 데모.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
예제를 선택하면 라이브 미리보기와 소스 코드를 나란히 표시하는 전체 화면이 열립니다.
값으로 넘긴 매개변수는 컴포넌트를 만들 때 딱 한 번 읽고, 함수로 넘긴 매개변수는 update()마다 다시 읽습니다. 어느 쪽이든 컴포넌트 자체는 한 번만 실행되며, 마운트 횟수가 그 증거입니다.
The mount count never moves: update() re-runs the functions and patches text. The static card keeps the values it was built with, by design.
import 'nuclo' let cart = 2 let user = { name: 'Ada', plan: 'Pro' } let updates = 0 let mounts = 0 const price = () => cart * 9 // Every component below carries mounted(). It counts each time a node // is built, and refreshes only the "stats" scope (not the whole page). const mounted = () => on('mount', () => { mounts++ queueMicrotask(() => update('stats')) }) const commit = () => { updates++; update() } const row = { style: { display: 'flex', flexWrap: 'wrap', gap: '6px' } } // A component is a plain function. What it is passed decides what // can change later: // a value is read once, when the component is built // a function is a dynamic value, read again on every update() // Either way the component itself runs once. update() never calls // it again; it only re-runs the functions inside it. function Stat(label: string, value: () => string | number) { return span(mounted(), label, ' ', b(() => String(value()))) } // Static: built with a snapshot. Rename the user and it stays "Ada". function Profile(u: { name: string; plan: string }) { return div( mounted(), div(h3(u.name), small('static: built with its values')), span(`plan ${u.plan}`), ) } // Dynamic: reads through a function, so a new user object shows up. function LiveProfile(u: () => { name: string; plan: string }) { return div( mounted(), div(h3(() => u().name), small('dynamic: reads a function')), span(() => `plan ${u().plan}`), ) } export const App = () => div( div(scope('stats'), span('mounts ', b(() => String(mounts))), span('updates ', b(() => String(updates)))), div(row, Stat('items', () => cart), Stat('price', () => `$${price()}`), Stat('user', () => user.name)), Profile(user), LiveProfile(() => user), div( row, button('Add item', { onClick: () => { cart++; commit() } }), button('Rename user', { onClick: () => { user = { ...user, name: user.name === 'Ada' ? 'Grace' : 'Ada' }; commit() }, }), button('Toggle plan', { onClick: () => { user = { ...user, plan: user.plan === 'Pro' ? 'Free' : 'Pro' }; commit() }, }), ), p('The mount count never moves: update() re-runs the functions and patches text. The static card keeps the values it was built with, by design.'), )