# @d1os/simple-wizard 中文文档

规范地址：https://npmcn.com/package/%40d1os/simple-wizard/

版本：1\.2\.0
npm 元数据更新时间：2026-03-28T02:47:43.247Z
中文译文更新时间：2026-11-11T07:52:16.984Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40d1os/simple-wizard
原文对照：https://npmcn.com/package/%40d1os/simple-wizard/?lang=original
项目主页：https://github.com/dcayers/simple-wizard#readme
源码仓库：https://github.com/dcayers/simple-wizard

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：52.2 kB，16 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：react ^18\.0\.0 \|\| ^19\.0\.0，react-dom ^18\.0\.0 \|\| ^19\.0\.0
- 首次发布：2026-01-04T10:53:03.843Z
- 最新版本发布：2026-03-28T02:47:43.127Z
- 近 30 天下载量：8733（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：3（近 12 个月 3 个）

## 中文简介

React 的简单向导组件

## 安装

```sh
npm install @d1os/simple-wizard
```

也可以使用：`pnpm add @d1os/simple-wizard`、`yarn add @d1os/simple-wizard`、`bun add @d1os/simple-wizard`

## README

# 简单 wizard

React 18和19的轻量级,灵活的向导组件.

## 安装

```bash
npm install @d1os/simple-wizard
```

```bash
yarn add @d1os/simple-wizard
```

```bash
pnpm add @d1os/simple-wizard
```

## 快速启动

```tsx
import { Wizard, useWizard } from "@d1os/simple-wizard";

function App() {
  return (
    <Wizard footer={<WizardFooter />}>
      <StepOne />
      <StepTwo />
      <StepThree />
    </Wizard>
  );
}

function WizardFooter() {
  const { nextStep, previousStep, activeStep, stepCount } = useWizard((state) => ({
    nextStep: state.nextStep,
    previousStep: state.previousStep,
    activeStep: state.activeStep,
    stepCount: state.stepCount,
  }));

  const isFirstStep = activeStep === 0;
  const isLastStep = activeStep === stepCount - 1;

  return (
    <div>
      <button onClick={() => previousStep()} disabled={isFirstStep}>
        Back
      </button>
      <button onClick={() => nextStep()} disabled={isLastStep}>
        {isLastStep ? "Finish" : "Next"}
      </button>
    </div>
  );
}
```

## API 密码

### `<Wizard />`

主要集装箱部分.

```tsx
interface WizardProps {
  children?: ReactNode;    // Step components
  header?: ReactNode;      // Rendered before steps
  footer?: ReactNode;      // Rendered after steps
  startAtEnd?: boolean;    // Start at last step (default: false)
  initialStep?: number;    // Starting step index (default: 0)
}
```

### `useWizard(selector)`

钩入巫师状态和行动。 使用选择器进行最佳重置.

```tsx
const { activeStep, nextStep } = useWizard((state) => ({
  activeStep: state.activeStep,
  nextStep: state.nextStep,
}));
```

#### 状态

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `activeStep` | `number` | 当前步骤指数(基于0) |
| `stepCount` | `number` | 步骤总数 |
| `isLoading` | `boolean` | 在同步动作中加载状态 |
| `nextButtonLabel` | `string` | 下一个按钮的标签( 默认为“ 下一步 ”) |
| `previousButtonLabel` | `string` | 上一个按钮的标签( 默认为“ 返回 ”) |
| `isNextButtonDisabled` | `boolean` | 是否禁用下一个按钮 |

#### 行动

| 行动 | 类型 | 说明 |
| --- | --- | --- |
| `nextStep(skip?)` | `(skip?: number) => void` | 转到下一步( 或跳过多个步骤) |
| `previousStep(skip?)` | `(skip?: number) => void` | 跳转到上一步( 或跳过多步) |
| `setActiveStep(step)` | `(step: number) => void` | 跳到特定的步骤 |
| `setIsLoading(loading)` | `(loading: boolean) => void` | 设定装入状态 |
| `setStepAction(handler)` | `(handler: () => void | Promise<void>) => void` | 在推进前设定要运行的动作 |
| `setNextButtonLabel(label)` | `(label: string) => void` | 设置下个按钮标签 |
| `setPreviousButtonLabel(label)` | `(label: string) => void` | 设置上一个按钮标签 |
| `setNextButtonDisabled(disabled)` | `(disabled: boolean) => void` | 禁用/ 可启用下一个按钮 |

## 实例

### Async 步骤验证

在推进下一步前运行同步验证 :

```tsx
function StepWithValidation() {
  const { setStepAction } = useWizard((state) => ({
    setStepAction: state.setStepAction,
  }));

  useEffect(() => {
    setStepAction(async () => {
      await saveFormData();
      // If this throws, navigation is cancelled
    });
  }, [setStepAction]);

  return <form>...</form>;
}
```

### 有条件跳过步骤

使用 `skip` 有条件跳过步骤的道具 :

```tsx
<Wizard>
  <StepOne />
  <StepTwo skip={!showOptionalStep} />
  <StepThree />
</Wizard>
```

### 自定义进度指标

```tsx
function ProgressBar() {
  const { activeStep, stepCount } = useWizard((state) => ({
    activeStep: state.activeStep,
    stepCount: state.stepCount,
  }));

  const progress = ((activeStep + 1) / stepCount) * 100;

  return (
    <div className="progress-bar">
      <div className="progress-fill" style={{ width: `${progress}%` }} />
      <span>{activeStep + 1} of {stepCount}</span>
    </div>
  );
}

// Usage
<Wizard header={<ProgressBar />}>
  ...
</Wizard>
```

### 控制导航

```tsx
function StepButtons() {
  const { activeStep, stepCount, setActiveStep } = useWizard((state) => ({
    activeStep: state.activeStep,
    stepCount: state.stepCount,
    setActiveStep: state.setActiveStep,
  }));

  return (
    <div className="step-buttons">
      {Array.from({ length: stepCount }, (_, i) => (
        <button
          key={i}
          onClick={() => setActiveStep(i)}
          className={activeStep === i ? "active" : ""}
        >
          {i + 1}
        </button>
      ))}
    </div>
  );
}
```

## 使用窗体库

`simple-wizard` 是形式-图书馆不可知论。 您可以使用任何您喜欢的表格库, 例如 `react-hook-form`, (中文(简体) ), `formik`, (中文(简体) ), `@tanstack/react-form`等 (中文(简体) ).

使用 `setStepAction()` 整合验证:

### 使用 `react-hook-form`

```tsx
import { useForm } from "react-hook-form";

function StepWithValidation() {
  const { register, trigger } = useForm();
  const { setStepAction } = useWizard((state) => ({
    setStepAction: state.setStepAction,
  }));


  useEffect(() => {
    setStepAction(async () => {
      const valid = await trigger();
      if (!valid) {
        throw new Error("Form is invalid");
      }
    });
  }, [setStepAction, trigger]);

  return (
    <input {...register("email", { required: true })} placeholder="Email" />
  );
}
```

### 使用 `@tanstack/react-form`

```tsx
import { useForm } from "@tanstack/react-form";

function StepWithValidation() {
  const form = useForm({
    defaultValues: {
      email: "",
    },
  });
  const { setStepAction } = useWizard((state) => ({
    setStepAction: state.setStepAction,
  }));

  useEffect(() => {
    setStepAction(async () => {
      await form.validateAllFields("change");
      if (!form.state.isFormValid) {
        throw new Error("Form is invalid");
      }
    });
  }, [setStepAction, form]);

  return (
    <form.Field name="email">
      {({ field }) => (
        <input {...field.getInputProps()} placeholder="Email" />
      )}
    </form.Field>
  )
}
```

一个使用 `@tanstack/react-form` 可见于 [这个堆起闪烁](https://stackblitz.com/edit/example-d1os-wizard-rhf-ttsg3fvk)。 。 。 .

## 反应19 最佳做法

这个库与React 19完全兼容. 这里的图案可以利用步骤组件中的19个特性:

### 使用 `use()` 用于获取数据

```tsx
import { use, Suspense } from "react";

function StepWithData({ dataPromise }) {
  const data = use(dataPromise);
  return <div>{data.content}</div>;
}

// In your wizard
<Wizard>
  <Suspense fallback={<Loading />}>
    <StepWithData dataPromise={fetchStepData()} />
  </Suspense>
</Wizard>
```

### 优化更新 `useOptimistic()`

```tsx
import { useOptimistic, useState } from "react";

function StepWithOptimisticSave() {
  const [saved, setSaved] = useState(false);
  const [optimisticSaved, setOptimisticSaved] = useOptimistic(saved);

  async function handleSave() {
    setOptimisticSaved(true);  // Instant UI feedback
    await saveToServer();
    setSaved(true);
  }

  return (
    <div>
      <button onClick={handleSave}>
        {optimisticSaved ? "Saved!" : "Save"}
      </button>
    </div>
  );
}
```

### 表格动作 `useActionState()`

```tsx
import { useActionState } from "react";

function FormStep() {
  const [state, submitAction, isPending] = useActionState(
    async (prevState, formData) => {
      const result = await submitForm(formData);
      return { success: result.ok, error: result.error };
    },
    { success: false, error: null }
  );

  return (
    <form action={submitAction}>
      <input name="email" type="email" required />
      {state.error && <p className="error">{state.error}</p>}
      <button type="submit" disabled={isPending}>
        {isPending ? "Submitting..." : "Continue"}
      </button>
    </form>
  );
}
```

## 类型脚本

导出类型的全类型脚本支持 :

```tsx
import type {
  WizardProps,
  WizardStore,
  WizardState,
  WizardActions
} from "@d1os/simple-wizard";
```

## 许可证

麻省理工学院

## 常见问题

### @d1os/simple-wizard 是什么？

React 的简单向导组件

### 如何安装 @d1os/simple-wizard？

在项目目录运行 npm install @d1os/simple-wizard，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^18\.0\.0 \|\| ^19\.0\.0）、react-dom（^18\.0\.0 \|\| ^19\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @d1os/simple-wizard 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @d1os/simple-wizard 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @d1os/simple-wizard 可以商用吗？

@d1os/simple-wizard 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @d1os/simple-wizard 的下载量有多少？

根据 npm 官方下载统计，@d1os/simple-wizard 在 2026/10/11 – 2026/11/09 这 30 天内被下载 8,733 次，日均约 291 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @d1os/simple-wizard 还在维护吗？

最新版本 1\.2\.0 发布于 2026/03/28（7 个月前）；至今共发布 3 个版本，其中过去 12 个月发布了 3 个；首次发布于 2026/01/04。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

