[英]Convert react JSX object to HTML
I have a react application that generates HTML output based on some configuration.我有一个基于某些配置生成 HTML 输出的 React 应用程序。 Like this:
像这样:
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 的方法...
Use renderToStaticMarkup method - it produces HTML strings that we can transfer to the wire quickly:使用renderToStaticMarkup方法 - 它生成 HTML 字符串,我们可以快速传输到线路:
const htmlString = ReactDOMServer.renderToStaticMarkup(
<div ...
);
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:注意事项:
ReactDOMServer.renderToStaticMarkup()
to get the HTML codeReactDOMServer.renderToStaticMarkup()
获取 HTML 代码ParentComponent.contextTypes
to make this.context.store availableParentComponent.contextTypes
使 this.context.store 可用Provider
so it has access to the redux store.Provider
以便它可以访问 redux 存储。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.