如何从渲染组件获取 HTML 输出

How to get the HTML output from a rendered component

我是 ReactJS 世界的新手,正在尝试进入它。我正在编写一个样式指南,我需要为其显示一些 HTML 代码作为示例。我正在为此使用 ReactPrism,但我无法在我的 PrismCode 组件中获得 HTML 输出,我通过使用显示 JSX 代码而不是 HTML 的 react-to-jsx 找到了解决方法. 这是代码:

import React from 'react';
import {PrismCode} from "react-prism";
import reactToJsx from 'react-to-jsx';

class CodePreview extends React.Component {
    render (){
        return (
            <div>
                {this.props.children}
                <h5>Code example</h5>
                <pre>
                    <PrismCode className="language-javascript">
                        {reactToJsx(this.props.children)}
                    </PrismCode>
                </pre>
            </div>
        );
    }
}

export default CodePreview;

所以基本上我想将 this.props.children(组件)渲染为 HTML 代码,而不是 PrismCode 中的内容 我什至尝试了 https://github.com/tomchentw/react-prism 上显示的以下内容,但它不起作用。不确定我做错了什么!

<PrismCode className="language-javascript">
    {require("raw-loader!./PrismCode")}
</PrismCode>

你考虑过用 markdown 写你的文档吗?我为反应添加了一些特殊标签:

```react:mirror
<Slider
  value={7}
/>
```

这将显示呈现的组件以及突出显示的 JSX 语法。

```react:demo
<PropsEditor>
  <Slider
    value={7}
  />
</PropsEditor>
```

这将渲染组件以及一个实时编辑器来操作组件上的任何道具。

```react
  <SomeComponent />
```

只会突出显示语法但不会呈现组件。

在我的降价文件的顶部,我可以导入我在文档中使用的任何组件:

---
imports:
  - import Slider from '../src/slider'
  - import PropsEditor from 'props-editor'
---

这种方式的优点是您的文档可以像普通的 markdown 一样工作,并且很容易获得 JSX,因为您将它作为字符串。

要获取 HTML 源代码 我有一个“查看源代码 </> 按钮,它在单击时动态打印格式化 html:

步骤是:

  • 点击获取反应组件html
  • 使用棱镜和美化器格式化 html
  • 将其插入 DOM

所以包装你的反应组件并引用节点:

<div ref={(n) => (this.fenceView = n)}>

然后单击在组件下方添加输出,相关位:

import prismjs from 'prismjs';
import beautify from 'xml-beautifier';

const RE_HTML_COMMENTS = /<!--[\s\S]*?-->/g;

removeCodeSource() {
  const existingHtmlCode = this.fenceView.querySelector('.fence-generated-html');
  if (existingHtmlCode) existingHtmlCode.remove();
}

renderCodeSource() {
  const html = this.fenceView.children[0].innerHTML.replace(RE_HTML_COMMENTS, '');
  const fenceCode = beautify(html, '  ');
  const highlightedCode = prismjs.highlight(fenceCode, prismjs.languages.html);
  this.removeCodeSource();
  this.fenceView.insertAdjacentHTML('beforeend',
    `<pre class="fence-generated-html language-html"><code>${highlightedCode}</code></pre>`);
}