在自定义构建插件中将JSX元素传递给故事书参数

时间:2020-02-07 10:56:32

标签: reactjs storybook

我正在构建自定义标签

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元素作为道具时,出现如下错误

enter image description here

如何将JSX元素传递给故事书参数?

1 个答案:

答案 0 :(得分:0)

找到方法:

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>)
  }
}
相关问题