关于 solidjs
solidjs 是一项用于构建用户界面的声明式 JavaScript 库,适合开发者使用。它通过编译模板生成真实 DOM,并以细粒度响应式更新取代虚拟 DOM。
主要功能
- 01细粒度响应式更新
- 02信号、效果与记忆值
- 03异步资源与复杂状态存储
- 04条件、列表及动态组件
- 05上下文与生命周期 API
- 06Solid Router 和 SolidStart 指南
适用场景
- 01构建响应式 JavaScript 界面
- 02管理派生值和异步数据
- 03处理嵌套状态与列表渲染
- 04查阅路由及全栈项目设置
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ suryavirkapur/ skills --skill solidjs安装后在 Claude Code 中输入/solidjs确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/api_reference.mdpatterns.mdrouting.mdsolidstart.md详细介绍
SolidJS 开发
SolidJS 是一个声明式 JavaScript 库,用于构建具有细粒度响应性的用户界面。与虚拟 DOM 框架不同,Solid 会将模板编译为真实 DOM 节点,并通过细粒度响应机制更新它们。
核心原则
- 组件只运行一次 — 组件函数仅在初始化期间执行,不会在每次更新时执行
- 细粒度响应性 — 只有依赖已更改数据的特定 DOM 节点会更新
- 没有虚拟 DOM — 通过编译后的模板直接操作 DOM
- 信号是函数 — 通过调用获取值:
count()而不是count
响应式原语
信号 — 基本状态
import { createSignal } from "solid-js";
const [count, setCount] = createSignal(0);
// Read value (getter)
console.log(count()); // 0
// Update value (setter)
setCount(1);
setCount(prev => prev + 1); // Functional update
选项:
const [value, setValue] = createSignal(initialValue, {
equals: false, // Always trigger updates, even if value unchanged
name: "debugName" // For devtools
});
Effects — 副作用
import { createEffect } from "solid-js";
createEffect(() => {
console.log("Count changed:", count());
// Runs after render, re-runs when dependencies change
});
主要行为:
- 首次运行:渲染后、浏览器绘制前
- 后续运行:跟踪的依赖项发生变化时
- SSR 或 hydration 期间不会运行
- 使用
onCleanup执行清理逻辑
Memos — 派生/缓存值
import { createMemo } from "solid-js";
const doubled = createMemo(() => count() * 2);
// Access like signal
console.log(doubled()); // Cached, only recalculates when count changes
在以下情况使用 memos:
- 派生值的计算开销较大
- 派生值会被多次访问
- 希望在结果未改变时阻止下游更新
Resources — 异步数据
import { createResource } from "solid-js";
const [user, { mutate, refetch }] = createResource(userId, fetchUser);
// In JSX
<Show when={!user.loading} fallback={<Loading />}>
<div>{user()?.name}</div>
</Show>
// Resource properties
user.loading // boolean
user.error // error if failed
user.state // "unresolved" | "pending" | "ready" | "refreshing" | "errored"
user.latest // last successful value
Stores — 复杂状态
用于需要细粒度更新的嵌套对象/数组:
import { createStore } from "solid-js/store";
const [state, setState] = createStore({
user: { name: "John", age: 30 },
todos: []
});
// Path syntax updates
setState("user", "name", "Jane");
setState("todos", todos => [...todos, newTodo]);
setState("todos", 0, "completed", true);
// Produce for immer-like updates
import { produce } from "solid-js/store";
setState(produce(s => {
s.user.age++;
s.todos.push(newTodo);
}));
Store 工具:
produce— 类似 Immer 的变更操作reconcile— 对数据进行差异比较和修补(用于 API 响应)unwrap— 获取原始的非响应式对象
组件
基本组件
import { Component } from "solid-js";
const MyComponent: Component<{ name: string }> = (props) => {
return <div>Hello, {props.name}</div>;
};
Props 处理
import { splitProps, mergeProps } from "solid-js";
// Default props
const merged = mergeProps({ size: "medium" }, props);
// Split props (for spreading)
const [local, others] = splitProps(props, ["class", "onClick"]);
return <button class={local.class} {...others} />;
Props 规则:
- Props 是响应式 getter — 不要在顶层解构
- 在 JSX 中使用
props.value,而不是const { value } = props
Children 辅助函数
import { children } from "solid-js";
const Wrapper: Component = (props) => {
const resolved = children(() => props.children);
createEffect(() => {
console.log("Children:", resolved());
});
return <div>{resolved()}</div>;
};
控制流组件
Show — 条件渲染
import { Show } from "solid-js";
<Show when={user()} fallback={<Login />}>
{(user) => <Profile user={user()} />}
</Show>
For — 列表渲染(按引用键控)
import { For } from "solid-js";
<For each={items()} fallback={<Empty />}>
{(item, index) => (
<div>{index()}: {item.name}</div>
)}
</For>
注意: index 是信号,item 是值。
Index — 列表渲染(按索引键控)
import { Index } from "solid-js";
<Index each={items()}>
{(item, index) => (
<input value={item().text} />
)}
</Index>
注意: item 是信号,index 是值。更适合原始值数组或输入框。
Switch/Match — 多条件判断
import { Switch, Match } from "solid-js";
<Switch fallback={<Default />}>
<Match when={state() === "loading"}>
<Loading />
</Match>
<Match when={state() === "error"}>
<Error />
</Match>
<Match when={state() === "success"}>
<Success />
</Match>
</Switch>
Dynamic — 动态组件
import { Dynamic } from "solid-js/web";
<Dynamic component={selected()} someProp="value" />
Portal — 在 DOM 层级之外渲染
import { Portal } from "solid-js/web";
<Portal mount={document.body}>
<Modal />
</Portal>
ErrorBoundary — 错误处理
import { ErrorBoundary } from "solid-js";
<ErrorBoundary fallback={(err, reset) => (
<div>
Error: {err.message}
<button onClick={reset}>Retry</button>
</div>
)}>
<RiskyComponent />
</ErrorBoundary>
Suspense — 异步加载
import { Suspense } from "solid-js";
<Suspense fallback={<Loading />}>
<AsyncComponent />
</Suspense>
Context API
import { createContext, useContext } from "solid-js";
// Create context
const CounterContext = createContext<{
count: () => number;
increment: () => void;
}>();
// Provider component
export function CounterProvider(props) {
const [count, setCount] = createSignal(0);
return (
<CounterContext.Provider value={{
count,
increment: () => setCount(c => c + 1)
}}>
{props.children}
</CounterContext.Provider>
);
}
// Consumer hook
export function useCounter() {
const ctx = useContext(CounterContext);
if (!ctx) throw new Error("useCounter must be used within CounterProvider");
return ctx;
}
生命周期
import { onMount, onCleanup } from "solid-js";
function MyComponent() {
onMount(() => {
console.log("Mounted");
const handler = () => {};
window.addEventListener("resize", handler);
onCleanup(() => {
window.removeEventListener("resize", handler);
});
});
return <div>Content</div>;
}
Refs
let inputRef: HTMLInputElement;
<input ref={inputRef} />
<input ref={(el) => { /* el is the DOM element */ }} />
事件处理
// Standard events (lowercase)
<button onClick={handleClick}>Click</button>
<button onClick={(e) => handleClick(e)}>Click</button>
// Delegated events (on:)
<input on:input={handleInput} />
// Native events (on:) - not delegated
<div on:scroll={handleScroll} />
路由(Solid Router)
完整路由指南请参阅 references/routing.md。
快速设置:
import { Router, Route } from "@solidjs/router";
<Router>
<Route path="/" component={Home} />
<Route path="/users/:id" component={User} />
<Route path="*404" component={NotFound} />
</Router>
SolidStart
全栈开发指南请参阅 references/solidstart.md。
快速设置:
npm create solid@latest my-app
cd my-app && npm install && npm run dev
常见模式
条件类名
import { clsx } from "clsx"; // or classList
<div class={clsx("base", { active: isActive() })} />
<div classList={{ active: isActive(), disabled: isDisabled() }} />
批量更新
import { batch } from "solid-js";
batch(() => {
setName("John");
setAge(30);
// Effects run once after batch completes
});
Untrack
import { untrack } from "solid-js";
createEffect(() => {
console.log(count()); // tracked
console.log(untrack(() => other())); // not tracked
});
TypeScript
import type { Component, ParentComponent, JSX } from "solid-js";
// Basic component
const Button: Component<{ label: string }> = (props) => (
<button>{props.label}</button>
);
// With children
const Layout: ParentComponent<{ title: string }> = (props) => (
<div>
<h1>{props.title}</h1>
{props.children}
</div>
);
// Event handler types
const handleClick: JSX.EventHandler<HTMLButtonElement, MouseEvent> = (e) => {
console.log(e.currentTarget);
};
项目设置
# Create new project
npm create solid@latest my-app
# With template
npx degit solidjs/templates/ts my-app
# SolidStart
npm create solid@latest my-app -- --template solidstart
vite.config.ts:
import { defineConfig } from "vite";
import solid from "vite-plugin-solid";
export default defineConfig({
plugins: [solid()]
});
应避免的反模式
-
解构 props — 会破坏响应性
// ❌ Bad const { name } = props; // ✅ Good props.name -
在跟踪范围之外访问信号
// ❌ Won't update console.log(count()); // ✅ Will update createEffect(() => console.log(count())); -
忘记调用信号 getter
// ❌ Passes the function <div>{count}</div> // ✅ Passes the value <div>{count()}</div> -
使用数组索引作为键 — 引用键控使用
<For>,索引键控使用<Index> -
在渲染期间执行副作用 — 使用
createEffect或onMount
评论
支持 Markdown