【问题标题】:How to get the HTML output from a rendered component如何从渲染的组件中获取 HTML 输出
【发布时间】:2017-04-24 17:30:52
【问题描述】:

我是 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>

【问题讨论】:

  • 感谢您的回复,我已经尝试过了,但它不起作用,因为 this.props.children 传递了一个我需要 HTML 输出的对象

标签: html reactjs react-jsx prism.js


【解决方案1】:

您是否考虑过使用 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'
---

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

要获取 HTML 源代码,我有一个“查看源代码&lt;/&gt;”按钮,点击时会动态打印格式化的 html:

步骤如下:

  • 点击获取react组件的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>`);
}

【讨论】:

  • 我想做的是以下几点:我有一些反应组件,如按钮、输入元素、表单等,我想在页面上显示该组件以及它的 HTML 代码。所以 this.props.children 渲染了组件,但是不知道如何从渲染的对象中获取 HTML 在这种情况下 this.props.children。
  • 使用组件的 ref 很容易,然后使用 vanilla javascript 获取 html 并使用 prism 对其进行格式化,我将发布一个示例,我会做同样的事情
猜你喜欢
  • 2021-01-22
  • 2021-07-11
  • 2020-01-31
  • 2015-11-08
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
相关资源
最近更新 更多