How to render (print) JSX as String?

你。 提交于 2020-02-23 08:57:09

问题


Here JSX is scode sample:

export default class Element extends React.Component {
  render() {
    return (
      <div>
        <div className="alert alert-success">
          {this.props.langs.map((lang, i) => <span key={i} className="label label-default">{lang}</span>)}
        </div>
      </div>
    )
  }
}

How to get string like this?

<div><div className="alert alert-success">{this.props.langs.map((lang, i) => <span key={i} className="label label-default">{lang}</span>)}</div></div>

UPD: I got React components which I render on the server. I want to get them as a strings to transform them for another templating library on client side.


回答1:


just call renderToStaticMarkup() and you should get the static html markup language generated by React.

somewhat like this:

import ReactDOMServer from 'react-dom/server';
import Element from './path/to/element/class';

const element = <Element />;

ReactDOMServer.renderToStaticMarkup(element)

here are some more docs about this:

https://facebook.github.io/react/docs/react-dom-server.html#rendertostaticmarkup



来源:https://stackoverflow.com/questions/43416939/how-to-render-print-jsx-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!