Next.js 路由器

在您的 Storybook 故事中使用 Next.js 路由器。

在 Github 上檢視

您可能不需要這個專案

https://storybook.dev.org.tw/blog/integrate-nextjs-and-storybook-automatically/

Storybook 擴充套件 Next Router

在您的 Storybook 故事中使用 Next.js 路由器。

版本

  • 如果您使用 storybook 5.x,請使用 1.x
  • 如果您使用 storybook 6.x,請使用 3.x
  • 如果您使用 storybook 6.x 和 react 18,請使用 4.x

注意:這些文件指的是 3.0

將擴充套件添加到您的設定檔 .storybook/main.js

module.exports = {
  ...config,
  addons: [
    ...your addons
    "storybook-addon-next-router",
  ],
};

將 RouterContext.Provider 添加到 .storybook/preview.js

import { AppRouterContext } from "next/dist/shared/lib/app-router-context"; // next 13 next 13 (using next/navigation)
// import { RouterContext } from "next/dist/shared/lib/router-context"; // next 13 (using next/router) / next 12
// import { RouterContext } from "next/dist/shared/lib/router-context"; // next 11.1
// import { RouterContext } from "next/dist/next-server/lib/router-context"; // next < 11.1

export const parameters = {
  nextRouter: {
    Provider: AppRouterContext.Provider, // next 13 next 13 (using next/navigation)
    // Provider: RouterContext.Provider, // next 13 (using next/router) / next < 12
  },
}

在故事中的用法

import MyComponentThatHasANextLink from "../component-that-has-a-next-link";

export default {
  title: "My Story",
};

// if you have the actions addon
// you can click the links and see the route change events there
export const Example = () => <MyComponentThatHasANextLink />;

Example.parameters = {
  nextRouter: {
    pathname: "/profile/[id]",
    asPath: "/profile/lifeiscontent",
    query: {
      id: "lifeiscontent",
    },
  },
};

自訂預設值

preview.js

export const parameters = {
    nextRouter: {
        pathname: '/', // defaults to `/`
        asPath: '/', // defaults to `/`
        query: {}, // defaults to `{}`
        push() {
        } // defaults to using addon actions integration,
        //   can override any method in the router
    }
};

請在 https://nextjs.dev.org.tw/docs/api-reference/next/router 閱讀更多關於 next/router 可用的選項

範例應用程式

若要查看如何使用此擴充套件的實際使用情況,請查看範例應用程式

https://github.com/lifeiscontent/realworld