加入直播会话:周四,美国东部时间上午 11 点,Storybook 9 发布及 AMA 问答

Next.js 路由

在您的 Storybook stories 中使用 Next.js Router。

在 Github 上查看

您可能不需要此项目

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

Storybook Addon Next Router

在您的 Storybook stories 中使用 Next.js Router。

版本

  • 如果您使用 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
  },
}

在 story 中的用法

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
    }
};

阅读更多关于 next/router 可用选项的信息,请访问 https://nextjs.net.cn/docs/api-reference/next/router

示例应用

要查看此插件的实际使用方法,请查看示例应用

https://github.com/lifeiscontent/realworld