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

React Runner

提供由 react-runner 驱动的 React 实时预览的 Storybook 插件

在 Github 上查看

React Runner Storybook 插件

提供由 react-runner 驱动的 React 实时预览的 Storybook 插件,试试 实时示例

安装

# Yarn
yarn add storybook-addon-react-runner

# NPM
npm install --save storybook-addon-react-runner

然后将插件添加到你的配置文件 .storybook/main.js

module.exports = {
  addons: ["storybook-addon-react-runner"],
};

配置

通过在 .storybook/preview.js 中添加以下内容来配置 scope 及更多选项

import * as components from "../your-components";

export const parameters = {
  reactRunner: {
    disable, // whether to disable the addon
    scope: {
      ...components,
      ...otherScope,
    },
    wrapper, // pass a React Component to have it rendered around the story
    language, // defautls to `jsx`, set to `tsx` to support typescript
    theme, // https://github.com/FormidableLabs/prism-react-renderer#theming
    readOnly, // code editor will be readonly if set to `true`
  },
};

你可以基于故事或组件更改配置

注意:如果你通过全局参数设置了 scope,则HMR(热模块替换)将不起作用,会执行完全重载

使用方法

用你喜欢的方式或直接用源代码编写你的故事

export const Source = {
  parameters: {
    storySource: {
      source: `<Button label="Source code" />`,
    },
  },
};

或者甚至包含 import 语句的真实示例

import ButtonStory from "./Button.story";
import ButtonStorySource from "!!raw-loader!./Button.story";

export const Complex = ButtonStory;
Complex.parameters = {
  storySource: {
    source: ButtonStorySource,
  },
  reactRunner: {
    // you can define your scope in `.storybook/preview.js`
    scope: {
      import: {
        react: React,
        "./Button": { Button },
      },
    },
  },
};

Button.story.js

import { useState } from "react";
import { Button } from "./Button";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <>
      <div>{count}</div>
      <Button label="+" onClick={() => setCount((count) => count + 1)} />
      <Button label="-" onClick={() => setCount((count) => count - 1)} />
    </>
  );
}

装饰器

此插件仅适用于全局装饰器,对于组件或故事装饰器,你可以使用 wrapper 作为替代方案

export default {
  title: "Example/Button",
  component: Button,
  parameters: {
    reactRunner: {
      wrapper: YourProvider,
    },
  },
};