Javascript 将 React JSX 对象转换为 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39308011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert react JSX object to HTML
提问by Philipp
I have a react application that generates HTML output based on some configuration. Like this:
我有一个基于某些配置生成 HTML 输出的 React 应用程序。像这样:
export const getHtml = (config) => {
const {classes, children} = config
return (<div className={classes.join(' ')}>{children}</div>);
}
Inside the react app I can easily display the resulting DOM objects, but I want to save the HTML code to DB, to display it on a different page (without loading react/parsing the config again)
在 react 应用程序中,我可以轻松显示生成的 DOM 对象,但我想将 HTML 代码保存到 DB,以将其显示在不同的页面上(无需再次加载 react/解析配置)
I could not find a way to convert the JSX object to plain HTML...
我找不到将 JSX 对象转换为纯 HTML 的方法...
回答by Igorsvee
Use renderToStaticMarkupmethod - it produces HTML strings that we can transfer to the wire quickly:
使用renderToStaticMarkup方法 - 它生成 HTML 字符串,我们可以快速传输到线路:
const htmlString = ReactDOMServer.renderToStaticMarkup(
<div ...
);
回答by Philipp
redux code:
还原代码:
Here is the full code that I had to use in my react/redux application.
这是我必须在我的 react/redux 应用程序中使用的完整代码。
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {Provider} from 'react-redux';
...
class ParentComponent extends React.Component {
...
getHtml(config) {
const {classes, children} = config
return ReactDOMServer.renderToStaticMarkup(
<Provider store={this.context.store}>
<ChildComponent classes={classes}>{children}</ChildComponent>
</Provider>
)
}
}
ParentComponent.contextTypes = { store: React.PropTypes.object };
Notes:
笔记:
- Use
ReactDOMServer.renderToStaticMarkup()
to get the HTML code - Specify
ParentComponent.contextTypes
to make this.context.store available - Need to wrap the ChildComponent in a
Provider
so it has access to the redux store.
- 使用
ReactDOMServer.renderToStaticMarkup()
获得的HTML代码 - 指定
ParentComponent.contextTypes
使 this.context.store 可用 - 需要将 ChildComponent 包装在 a 中,
Provider
以便它可以访问 redux 存储。