将元素转换为字符串

时间:2019-06-11 16:55:23

标签: reactjs

如何将React元素转换为字符串:

const e = React.createElement;

const _notification = e(
  "div", null, e(
    "button", null, "Foo"
  )
);

我需要这个:

const notification = someReactMethod(_notification);
console.log(notification);  // => "<div><button>Foo</button></div>"

注意:我不能再使用Node.js(这是我使用React的方式)。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用ReactDOMServer的静态方法。 renderToStringrenderToStaticMarkup

import ReactDOMServer from 'react-dom/server';
const notification = ReactDOMServer.renderToString(_notification);
// or
const notification = ReactDOMServer.renderToStaticMarkup(_notification);

对于静态页面,建议使用后者;如果要将标记合并到客户端的应用程序中,则需要使用前者。

相关问题