参加直播会议:美国东部时间周四上午 11 点,Storybook 9 发布与 AMA

一个 React Native Storybook 插件,用于为您的预览显示不同的背景

在 Github 上查看

Storybook for React Native

[!重要]
本 README 适用于 v9 测试版,v8 文档请参见v8.6 文档

使用 Storybook for React Native,您可以在不运行应用程序的情况下设计和开发独立的 React Native 组件。

如果您正在从 8 迁移到 9,可以在这里找到迁移指南

有关 Storybook 的更多信息,请访问:storybook.js.org

[!注意]
请确保您的 Storybook 依赖项对齐到相同的主版本,否则您将看到错误的行为。

picture of storybook

目录

入门

新项目

这里有一些项目样板,其中已配置了 @storybook/react-native@storybook/addon-react-native-web 以及一个简单的示例。

对于 expo,您可以使用此模板,使用以下命令:

# With NPM
npx create-expo-app --template expo-template-storybook AwesomeStorybook

对于 react native cli,您可以使用此模板

npx react-native init MyApp --template react-native-template-storybook

现有项目

运行 init 来设置您的项目,包括所有依赖项和配置文件

npx storybook@latest init

剩下的唯一事情就是在您的应用入口点(例如 App.tsx)中返回 Storybook 的 UI,如下所示

export { default } from './.storybook';

然后使用 withStorybook 函数包装您的 metro config,如下所示

如果您想轻松地在 Storybook 和您的应用之间切换,请查看此博客文章

如果您想手动添加所有内容,请查看此处的手动指南。

附加步骤:更新您的 metro config

我们需要 unstable_allowRequireContext 转换器选项来启用基于 main.ts 中的故事全局表达式的动态故事导入。我们还可以从 metro config 中调用 Storybook 生成函数,以便在 metro 运行时自动生成 storybook.requires.ts 文件。

Expo

如果您还没有 metro config 文件,请先创建它。

npx expo customize metro.config.js

然后使用 withStorybook 函数包装您的 config,如下所示。

// metro.config.js
const path = require('path');
const { getDefaultConfig } = require('expo/metro-config');
const withStorybook = require('@storybook/react-native/metro/withStorybook');

/** @type {import('expo/metro-config').MetroConfig} */
const config = getDefaultConfig(__dirname);

module.exports = withStorybook(config, {
  // Set to false to remove storybook specific options
  // you can also use a env variable to set this
  enabled: true,
  // Path to your storybook config
  configPath: path.resolve(__dirname, './.storybook'),

  // Optional websockets configuration
  // Starts a websocket server on the specified port and host on metro start
  // websockets: {
  //   port: 7007,
  //   host: 'localhost',
  // },
});

React Native

const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const path = require('path');
const withStorybook = require('@storybook/react-native/metro/withStorybook');
const defaultConfig = getDefaultConfig(__dirname);

/**
 * Metro configuration
 * https://reactnative.net.cn/docs/metro
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {};
// set your own config here 👆

const finalConfig = mergeConfig(defaultConfig, config);

module.exports = withStorybook(finalConfig, {
  // Set to false to remove storybook specific options
  // you can also use a env variable to set this
  enabled: true,
  // Path to your storybook config
  configPath: path.resolve(__dirname, './.storybook'),

  // Optional websockets configuration
  // Starts a websocket server on the specified port and host on metro start
  // websockets: {
  //   port: 7007,
  //   host: 'localhost',
  // },
});

Reanimated 设置

确保您的项目中包含 react-native-reanimated 并在 babel config 中设置了该插件。

// babel.config.js
plugins: ['react-native-reanimated/plugin'],

编写故事

在 Storybook 中,我们使用一种称为 CSF 的语法,它看起来像这样

import type { Meta, StoryObj } from '@storybook/react';
import { MyButton } from './Button';

const meta = {
  component: MyButton,
} satisfies Meta<typeof MyButton>;

export default meta;

type Story = StoryObj<typeof meta>;

export const Basic: Story = {
  args: {
    text: 'Hello World',
    color: 'purple',
  },
};

您应该在 .storybook 文件夹中的 main.ts 配置文件中配置您的故事文件的路径。

// .storybook/main.ts
import { StorybookConfig } from '@storybook/react-native';

const main: StorybookConfig = {
  stories: ['../components/**/*.stories.?(ts|tsx|js|jsx)'],
  addons: [],
};

export default main;

装饰器和参数

对于故事,您可以在默认导出或特定故事上添加装饰器和参数。

import type { Meta } from '@storybook/react';
import { Button } from './Button';

const meta = {
  title: 'Button',
  component: Button,
  decorators: [
    (Story) => (
      <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>
        <Story />
      </View>
    ),
  ],
  parameters: {
    backgrounds: {
      values: [
        { name: 'red', value: '#f00' },
        { name: 'green', value: '#0f0' },
        { name: 'blue', value: '#00f' },
      ],
    },
  },
} satisfies Meta<typeof Button>;

export default meta;

对于全局装饰器和参数,您可以将它们添加到 .storybook 文件夹中的 preview.tsx 中。

// .storybook/preview.tsx
import type { Preview } from '@storybook/react';
import { withBackgrounds } from '@storybook/addon-ondevice-backgrounds';

const preview: Preview = {
  decorators: [
    withBackgrounds,
    (Story) => (
      <View style={{ flex: 1, color: 'blue' }}>
        <Story />
      </View>
    ),
  ],
  parameters: {
    backgrounds: {
      default: 'plain',
      values: [
        { name: 'plain', value: 'white' },
        { name: 'warm', value: 'hotpink' },
        { name: 'cool', value: 'deepskyblue' },
      ],
    },
  },
};

export default preview;

插件

CLI 将为您安装一些基本插件,例如 controls 和 actions。设备端插件是可以在您在手机上看到的设备 UI 中渲染的插件。

当前可用的插件有

安装您想使用的每个插件,并将其添加到 main.ts 插件列表中,如下所示

// .storybook/main.ts
import { StorybookConfig } from '@storybook/react-native';

const main: StorybookConfig = {
  // ... rest of config
  addons: [
    '@storybook/addon-ondevice-notes',
    '@storybook/addon-ondevice-controls',
    '@storybook/addon-ondevice-backgrounds',
    '@storybook/addon-ondevice-actions',
  ],
};

export default main;

在您的故事中使用插件

有关每个设备端插件的详细信息,您可以查看 README

隐藏/显示 Storybook

React Native 上的 Storybook 是一个普通的 React Native 组件,可以根据您自己的逻辑在您的 RN 应用程序中的任何位置使用或隐藏。

您还可以创建一个单独的应用程序专门用于 Storybook,该应用程序也可用作您的视觉组件的包。有些人选择通过使用 React Native 开发人员菜单中的自定义选项来切换 Storybook 组件。

withStorybook 包装器

withStorybook 是一个包装函数,用于为 Storybook 扩展您的Metro config。它接受您现有的 Metro config 和一个包含 Storybook 启动和配置选项的对象。

// metro.config.js
const { getDefaultConfig } = require('expo/metro-config');
const withStorybook = require('@storybook/react-native/metro/withStorybook');

const defaultConfig = getDefaultConfig(__dirname);

module.exports = withStorybook(defaultConfig, {
  enabled: true,
  // See API section below for available options
});

选项

enabled

类型:boolean,默认值:true

确定是否将指定的选项应用于 Metro config。这对于同时使用 Metro 和 Storybook,并且需要有条件地应用选项的项目设置非常有用。在此示例中,它通过环境变量进行了条件设置

// metro.config.js
const { getDefaultConfig } = require('expo/metro-config');
const withStorybook = require('@storybook/react-native/metro/withStorybook');

const defaultConfig = getDefaultConfig(__dirname);

module.exports = withStorybook(defaultConfig, {
  enabled: process.env.WITH_STORYBOOK,
  // ... other options
});

onDisabledRemoveStorybook

类型:boolean,默认值:false

如果 onDisabledRemoveStorybooktrueenabledfalse,则 Storybook 包将从构建中移除。这对于您想从生产构建中移除 Storybook 非常有用。

useJs

类型:boolean,默认值:false

以 JavaScript 而非 TypeScript 生成 .storybook/storybook.requires 文件。

configPath

类型:string,默认值:path.resolve(process.cwd(), './.storybook')

您的 Storybook 配置目录的位置,其中包含 main.ts 和其他项目相关文件。

websockets

类型:{ host: string?, port: number? },默认值:undefined

如果指定,在启动时创建一个 WebSocket 服务器。这允许您同步多个设备以显示相同的故事和连接到 UI 中的故事的arg值。

websockets.host

类型:string,默认值:'localhost'

如果指定,运行 WebSocket 的主机。

websockets.port

类型:number,默认值:7007

如果指定,运行 WebSocket 的端口。

getStorybookUI 选项

您可以在 Storybook 入口点调用 getStorybookUI 时传递这些参数

{
    initialSelection?: string | Object (undefined)
        -- initialize storybook with a specific story.  eg: `mybutton--largebutton` or `{ kind: 'MyButton', name: 'LargeButton' }`
    storage?: Object (undefined)
        -- {getItem: (key: string) => Promise<string | null>;setItem: (key: string, value: string) => Promise<void>;}
        -- Custom storage to be used instead of AsyncStorage
    onDeviceUI?: boolean;
        -- show the ondevice ui
    enableWebsockets?: boolean;
        -- enable websockets for the storybook ui
    query?: string;
        -- query params for the websocket connection
    host?: string;
        -- host for the websocket connection
    port?: number;
        -- port for the websocket connection
    secured?: boolean;
        -- use secured websockets
    shouldPersistSelection?: boolean;
        -- store the last selected story in the device's storage
    theme: Partial<Theme>;
        -- theme for the storybook ui
}

在单元测试中使用故事

Storybook 提供了测试工具,允许您在 Jest 等外部测试环境中重用您的故事。这样一来,您可以更轻松地编写单元测试,并重用 Storybook 中已完成的设置,但用于单元测试。您可以在可移植故事部分找到更多信息。

贡献

我们欢迎对 Storybook 的贡献!

  • 📥 Pull requests 和 🌟 Stars 总是受欢迎的。
  • 阅读我们的贡献指南以开始,或在 Discord 上找到我们,寻找 react-native 频道。

正在寻找第一个要解决的问题?

  • 我们将我们认为非常适合对 codebase 或一般开源软件新手的问题标记为 Good First Issue
  • 与我们交流,我们会找到适合您技能和学习兴趣的东西。

示例

这里有一些示例项目可以帮助您入门

制作者
  • ndelangen
    ndelangen
  • shilman
    shilman
  • tmeasday
    tmeasday
  • ghengeveld
    ghengeveld
  • winkervsbecks
    winkervsbecks
  • yannbf
    yannbf
标签