简体   繁体   English

React 的故事书显示纯 HTML 源代码<preview>添加在</preview>

[英]Storybook for React to show plain HTML source code with <Preview> Addon

I am using Preview addon in Storybook for React to show the component usage in Docs.我在 Storybook for React 中使用Preview addon 来显示 Docs 中的组件用法。

<Preview withToolbar>
  <Story name="primary">
  <PrimaryButton  disabled={boolean("Disabled",false)} modifiers={["small"]} onClick={action('button-click')} > {text("Label", "Hello Storybook")}</PrimaryButton>
  </Story>
</Preview>

This generate doc as below:这生成文档如下: 在此处输入图像描述 There is a show code/ hide code switch which shows the React Code for the component, is it possible to show the plain HTML markup as well.有一个显示代码/隐藏代码开关,它显示组件的 React 代码,是否也可以显示普通的 HTML 标记。

I need to use a single storybook component explorer for React and non React Projects so wanted to check if plain markup source code be generated as well.我需要为 React 和非 React 项目使用单个故事书组件浏览器,因此想检查是否也生成了纯标记源代码。

Thanks谢谢

I am in a similar situation where I just want to use react for the development of the stories and only display the HTML in the docs so it can be used with other frameworks.我处于类似的情况,我只想使用 React 来开发故事,并且只在文档中显示 HTML,以便它可以与其他框架一起使用。

This is what I came up with so far.到目前为止,这是我想出的。

In .storybook/preview.js I am using a custom function to render the source code so the file look something like this:.storybook/preview.js中,我使用自定义 function 来呈现源代码,因此文件看起来像这样:

import renderToHTML from './renderToHTML'

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
  docs: {
    transformSource: (src, storyContext) => renderToHTML(storyContext.storyFn),
  },
}

this is documented here .这记录在这里

My renderToHTML function is defined like this:我的renderToHTML function 定义如下:

import { renderToStaticMarkup } from 'react-dom/server'
import { AllHtmlEntities } from 'html-entities'
import prettier from 'prettier'
import HTMLParser from 'prettier/parser-html'
const entities = new AllHtmlEntities()

export default (story) =>
  prettier.format(entities.decode(renderToStaticMarkup(story())), {
    parser: 'html',
    plugins: [HTMLParser],
  })

I'm using renderToStaticMarkup to compile the story, then html-entities to unescape it and then using prettier to format it.我正在使用renderToStaticMarkup来编译故事,然后使用html-entities对其进行转义,然后使用prettier对其进行格式化。

I am still experimenting with this so I might update the answer if I found issues or a better way to do things我仍在试验这个,所以如果我发现问题或更好的做事方式,我可能会更新答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM