SolidJS 提供了多种控制流组件,用于条件渲染和列表渲染:
条件渲染:
javascript// Show - 条件渲染(类似 React 的条件渲染) <Show when={isLoggedIn()} fallback={<Login />}> <Dashboard /> </Show> // Switch - 多条件分支 <Switch fallback={<NotFound />}> <Match when={status() === 'loading'}> <Loading /> </Match> <Match when={status() === 'success'}> <Success /> </Match> <Match when={status() === 'error'}> <Error /> </Match> </Switch>
列表渲染:
javascript// For - 列表渲染(推荐使用) <For each={items()}> {(item, index) => ( <div> {index()}: {item.name} </div> )} </For> // Index - 使用索引作为 key(性能更好) <Index each={items()}> {(item, index) => ( <div> {index}: {item().name} </div> )} </Index>
动态组件:
javascript// Dynamic - 动态组件渲染 <Dynamic component={currentComponent()} props={props} /> // Portal - 传送门到其他 DOM 节点 <Portal mount={document.getElementById('modal-root')}> <Modal /> </Portal>
Suspense - 异步加载:
javascript<Suspense fallback={<Loading />}> <AsyncComponent /> </Suspense> // 嵌套 Suspense <Suspense fallback={<Skeleton />}> <Suspense fallback={<LoadingAvatar />}> <UserAvatar /> </Suspense> <Suspense fallback={<LoadingPosts />}> <UserPosts /> </Suspense> </Suspense>
ErrorBoundary - 错误边界:
javascript<ErrorBoundary fallback={(err) => <ErrorPage error={err} />}> <Component /> </ErrorBoundary>
最佳实践:
- 使用
For而不是map进行列表渲染 - 使用
Index当列表项顺序不变时 - 使用
Show进行简单条件判断 - 使用
Switch处理多条件分支 - 使用
Suspense处理异步组件