Jotai

一个 Storybook 插件,允许您使用和模拟依赖于 Jotai 的 React 组件。

在 Github 上查看

Storybook Jotai 插件

一个用于 Storybook v8 的插件和装饰器,用于 Jotai 的模拟并在 Storybook 面板中显示当前值。

如果您希望设置 parameters 以实现强类型,请参阅 @alexgorbatchev/storybook-parameters

安装

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

.storybook/main.js 中注册插件

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

重要

请记住,该插件使用 jotai 包中的 Provider 包装所有内容。重要的是,您的故事组件不应包含 Provider,否则插件将无法查看和设置原子值。

用法

给定一个简单的组件

import { useAtom, atom } from 'jotai';

const userAtom = atom(null);

export const Header = () => {
  const [user] = useAtom(userAtom);

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

您可以编写一个故事,例如

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

import { User, userAtom } from './User';

type Story = StoryObj<typeof Header>;

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

export default meta;

export const JohnLoggedIn: Story = {
  parameters: {
    jotai: atomsForStorybook({
      atoms: {
        user: userAtom,
      },
      values: {
        user: {
          name: 'John Doe',
        },
      },
    }),
  },
};

// `jotai`, `atoms`, and `values` each can be a function for deferred evaluation.
export const JaneLoggedIn: Story = {
  parameters: {
    jotai: () => atomsForStorybook({
      atoms: () => ({
        user: userAtom,
      }),
      values: () => ({
        user: {
          name: 'Jane Doe',
        },
      }),
    }),
  };
};

export const LoggedOut: Story = {};

强类型示例

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

import { User, userAtom } from './User';

interface StoryParameters extends JotaiParameters {}

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

export default meta;

type Story = StoryObj<typeof Header, StoryParameters>;

export const JohnLoggedIn: Story = {
  parameters: {
    // `jotai` is strongly typed
    jotai: atomsForStorybook({
      atoms: {
        user: userAtom,
      },
      values: {
        user: {
          name: 'Jane Doe',
        },
      },
    }),
  },
};

开发脚本

  • npm run storybook 启动 Storybook
  • tsup 构建 ./dist
作者
  • alexgorbatchev
    alexgorbatchev
与之配合使用
    React
标签