Storybook for React Native
[!重要]
此 README 文件适用于 v9 beta 版本,v8 文档请参阅 v8.6 文档。
使用 Storybook for React Native,你无需运行应用即可设计和开发独立的 React Native 组件。
如果你正在从 8 迁移到 9,可以在 这里 找到迁移指南
有关 storybook 的更多信息,请访问:storybook.js.org
[!注意]
请确保你的 storybook 依赖项与 Storybook 主要版本保持一致,否则可能会出现异常行为。
目录
- 🚀 开始使用
- 📒 编写故事
- 🔌 插件
- 📱 隐藏/显示 Storybook
- ⚙️ withStorybook 包装器
- 🔧 getStorybookUI
- 🧪 在单元测试中使用故事
- 🤝 贡献
- ✨ 示例
开始使用
新项目
提供了一些项目模板,其中 @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 配置,如 下文 所示
如果你想在 storybook 和你的应用之间轻松切换,请查看这篇 博客文章
如果你想自己添加所有内容,请查看这份手动指南 这里。
附加步骤:更新你的 Metro 配置
我们需要 unstable_allowRequireContext 转换器选项,以基于 main.ts
中的 stories glob 来启用动态故事导入。 我们还可以从 metro 配置中调用 storybook generate 函数,以便在 metro 运行时自动生成 storybook.requires.ts
文件。
Expo
如果还没有 metro 配置文件,请先创建它。
npx expo customize metro.config.js
然后使用 withStorybook 函数包装你的配置,如下所示。
// 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 配置中设置了相应的插件。
// 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。 Ondevice 插件是可以在手机设备 UI 上渲染的插件。
目前可用的插件有
@storybook/addon-ondevice-controls
:实时调整组件属性@storybook/addon-ondevice-actions
:使用将在 actions 面板中记录信息的 actions 来模拟 onPress 调用@storybook/addon-ondevice-notes
:为你的故事添加一些 Markdown,以帮助记录其用法@storybook/addon-ondevice-backgrounds
:改变 storybook 的背景,以便对照不同的背景比较组件的外观
安装你要使用的每个插件,并如下所示将它们添加到 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;
在你的故事中使用插件
有关每个 ondevice 插件的详细信息,请参阅其 readme 文件
隐藏/显示 storybook
Storybook 在 React Native 中是一个普通的 React Native 组件,你可以根据自己的逻辑在你的 RN 应用中的任何地方使用或隐藏它。
你还可以专门为 storybook 创建一个单独的应用,它同时也可以作为你的可视化组件的包。 有些人选择通过在 React Native 开发者菜单中添加一个自定义选项来切换 storybook 组件。
withStorybook 包装器
withStorybook
是一个包装函数,用于扩展你的 Metro 配置,以便用于 Storybook。它接受你现有的 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: true,
// See API section below for available options
});
选项
enabled
类型: boolean
,默认值: true
确定指定的选项是否应用于 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
如果 onDisabledRemoveStorybook 设置为 true
且 enabled
设置为 false
,则 storybook 包将从构建中移除。 如果你想从生产构建中移除 storybook,这将非常有用。
useJs
类型: boolean
,默认值: false
生成 JavaScript 格式的 .storybook/storybook.requires
文件,而不是 TypeScript 格式。
configPath
类型: string
,默认值: path.resolve(process.cwd(), './.storybook')
你的 Storybook 配置目录的位置,该目录包含 main.ts
和其他项目相关文件。
websockets
类型: { host: string?, port: number? }
,默认值: undefined
如果指定,将在启动时创建一个 WebSocket 服务器。 这使你能够同步多个设备以显示相同的故事和 arg 在 UI 中与故事连接的值。
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 中已完成的设置。你可以在 portable stories 部分找到更多信息。
贡献
我们欢迎对 Storybook 的贡献!
正在寻找第一个可以着手的议题?
- 我们将我们认为适合刚接触代码库或开源软件(OSS)的人员的议题标记为 Good First Issue。
- 联系我们,我们会找到适合你技能和学习兴趣的任务。
示例
这里有一些示例项目可以帮助你开始
- 由 @axeldelafosse 制作的单仓设置 https://github.com/axeldelafosse/storybook-rnw-monorepo
- Expo 设置 https://github.com/dannyhw/expo-storybook-starter
- React Native CLI 设置 https://github.com/dannyhw/react-native-storybook-starter
- 为 RN CLI 项目在原生文件中添加一个单独的入口点和开发者菜单项: https://github.com/zubko/react-native-storybook-with-dev-menu
- 想展示你自己的项目? 提交一个 PR 并将其添加到列表中!