localStorage

一个用于模拟和显示`localStorage`值的 Storybook v8 附加组件

在 Github 上查看

Storybook LocalStorage 附加组件

一个用于模拟和在 Storybook 面板中显示 window.localStorage 的当前值的 Storybook v8 附加组件和装饰器

如果你想设置强类型化的`parameters`,请查看 @alexgorbatchev/storybook-parameters.

安装

npm i --save-dev @alexgorbatchev/storybook-addon-localstorage

在 ` .storybook/main.js`中注册附加组件

export default {
  stories: ['../stories/**/*.stories.tsx'],
  addons: ['@alexgorbatchev/storybook-addon-localstorage'],
};

重要

  • 如果设置了 `parameters.localStorage`,则在填充值之前会调用 `localStorage.clear()`。
  • 传递给 `parameters.localStorage` 的值**必须是字符串**,因为 `localStorage` 只能使用字符串。你可以使用 `JSON.stringify`,或者使用附加组件提供的帮助程序函数 `localStorageForStorybook`。
  • 最后,需要注意的是,附加组件的工作原理是每 100 毫秒轮询和比较 `localStorage` 中模拟值的差异。

用法

给定一个简单的组件

export const Header = () => {
  const [user, setUser, { removeItem }] = useLocalStorage<{ name: string }>('user');

  return (
    <div>
      {user ? (
        <div>
          <div>{`Logged in as ${user.name}`}</div>
          <Button size="small" label="Log out" onClick={() => removeItem()} />
        </div>
      ) : (
        <div>
          <div>No one is signed in</div>
          <Button size="small" label="Log in" onClick={() => setUser({ name: 'John' })} />
        </div>
      )}
    </div>
  );
};

你可以这样编写故事

import { localStorageForStorybook } from '@alexgorbatchev/storybook-addon-localstorage';
import { Meta, StoryObj } from '@storybook/react';

import { Header } from './Header';

const meta: Meta<typeof Header> = {
  title: 'Example/Header',
  component: Header,
};

export default meta;

type Story = StoryObj<typeof Header>;

export const JohnLoggedIn: Story = {
  parameters: {
    // this helper automatically stringifies the values using `JSON.stringify`
    localStorage: localStorageForStorybook({
      value: 123,
      user: { name: 'John' },
    }),
  },
};

export const JaneLoggedIn: Story = {
  parameters: {
    // if you have own serialzer, you can use it as well
    localStorage: {
      value: '123',
      user: JSON.stringify({ name: 'Jane' }),
    },
  },
};

强类型示例

import { Meta, StoryObj } from '@alexgorbatchev/storybook-parameters';
import { LocalStorageParameters } from '@alexgorbatchev/storybook-addon-localstorage';

interface StoryParameters extends LocalStorageParameters {}

const meta: Meta<typeof Header, StoryParameters> = {
  title: 'Header',
  component: Header,
};

export default meta;

type Story = StoryObj<typeof Header, StoryParameters>;

export const JohnLoggedIn: Story = {
  parameters: {
    // `localStorage` will show up in `Parameters`
    localStorage: {
      key: 'value',
    },
  },
};

开发脚本

  • npm run storybook 启动 Storybook
  • tsup 构建 ` ./dist`