reactjs - 将 JSX 元素传递给自定义构建插件中的故事书参数
问题描述
我正在构建一个自定义选项卡
import React from 'react';
import { addons, types } from '@storybook/addons';
import { AddonPanel } from '@storybook/components';
import { useParameter } from '@storybook/api';
export const ADDON_ID = 'storybook/principles';
export const PANEL_ID = `${ADDON_ID}/panel`;
export const PARAM_KEY = 'principles'; // to communicate from stories
const PanelContent = () => {
const { component: Component } = useParameter(PARAM_KEY, {});
if (!Component) {
return <p>Usage info is missing</p>;
}
return <Component />;
};
addons.register(ADDON_ID, api => {
addons.add(PANEL_ID, {
type: types.Panel,
title: 'Usage',
paramKey: PARAM_KEY,
render: ({ active, key }) => {
return (
<AddonPanel active={active} key={key}>
<PanelContent />
</AddonPanel>
);
},
});
});
然后在我的故事中使用它
storiesOf('Superman', module)
.addParameters({
component: Superman,
principles: {
component: <Anatomy />
},
})
.add('a story 1', () => <p>some data 1</p>)
.add('a story 2', () => <p>some data 2</p>)
我尝试传入 JSX 元素的部分,例如
principles: { component: <Anatomy /> }, // this does not work
principles: { component: 'i can pass in a string' }, // this does work
当我将 JSX 元素作为道具传递时,出现如下错误
如何将 JSX 元素传递给故事书参数?
解决方案
找到了一个方法:
regiter.js
import { deserialize } from 'react-serialize'; //<-- this allows json to jsx conversion
// ...constants definitions
...
const Explanation = () => {
const Explanations = useParameter(PARAM_KEY, null);
const { storyId } = useStorybookState();
const storyKey = storyId.split('--')?.[1];
const ExplanationContent = useMemo(() => {
if (storyKey && Explanations?.[storyKey])
return () => deserialize(JSON.parse(Explanations?.[storyKey]));
return () => <>No extra explanation provided for the selected story</>;
}, [storyKey, Explanations?.[storyKey]]);
return (
<div style={{ margin: 16 }}>
<ExplanationContent />
</div>
);
};
addons.register(ADDON_ID, () => {
addons.add(PANEL_ID, {
type: types.TAB,
title: ADDON_TITLE,
route: ({ storyId, refId }) =>
refId
? `/${ADDON_PATH}/${refId}_${storyId}`
: `/${ADDON_PATH}/${storyId}`,
match: ({ viewMode }) => viewMode === ADDON_PATH,
render: ({ active }) => (active ? <Explanation /> : null),
});
});
并在声明参数时:
{
parameters:{
component: serialize(<p>Hello world</p>)
}
}
推荐阅读
- url - 如何在电子表格中获取可编辑表单响应的 URL
- javascript - 如何使用 For 循环通过递增的 ID 来定位输入字段
- docker - Jenkins 错误安装 Xvfb 并再次运行 Cypress
- amazon-web-services - 在 x86 桌面上运行使用 ARMv7 基础映像构建的 Docker 映像时出现问题
- angular - PrimeNG 的 TableEdit 中的 EditMode 不起作用
- jquery - jQuery colorbox 和 iframe 在第一次尝试时不会相互覆盖
- c++ - 异步比顺序执行花费更长的时间
- angular - 发布方法无法正常工作,没有任何错误
- php - Laravel orderby 与关系
- c# - 获取 Unity Blend Tree 以根据玩家旋转(鼠标位置)进行更新