简体   繁体   English

你如何将 React 组件渲染为字符串

[英]How do you Render a React Component to a String

I am trying to figure out if I can "render" a React component to an HTML string.我想弄清楚是否可以将 React 组件“呈现”为 HTML 字符串。 It is likely that the word "render" is not correct, as it implies putting it on the actual dom itself, whereas I am saying that I want to create a formatted HTML string from a react component. “渲染”这个词很可能是不正确的,因为它意味着将它放在实际的 dom 本身上,而我是说我想从 react 组件创建一个格式化的 HTML 字符串。 Example:例子:

renderToString((
<CustomComponent>
 {children}
</CustomComponent>
))

renderToString would roughly return... renderToString 将大致返回...

"<div><ul><li>child1</li><li>child2</li?</ul></div>"

If it is possible to "render" React down to raw html elements (that are not on the dom) that would be usable as well.如果可以将 React “渲染”为原始 html 元素(不在 dom 上),那么这些元素也可以使用。

Background: In a React application that I am using, I am wrapping another non-React JavaScript library that manipulates and handles its own rendering.背景:在我使用的 React 应用程序中,我包装了另一个非 React JavaScript 库,该库操作和处理自己的渲染。 Currently React is being used to build controllers that manipulate the creation of objects for this library.目前,React 被用于构建控制器来操作该库的对象创建。

This library allows callback functions for creating HTML elements (as strings) that it then uses to embed onto a canvas that it manipulates.这个库允许回调函数来创建 HTML 元素(作为字符串),然后它用来嵌入到它操作的画布上。

I would like to use proper JSX to build the strings.我想使用适当的 JSX 来构建字符串。

Any ideas?有任何想法吗?

Sounds like you're looking for ReactDOMServer.renderToStaticMarkup() or ReactDOMServer.renderToString() .听起来您正在寻找ReactDOMServer.renderToStaticMarkup()ReactDOMServer.renderToString() Both of the functions can be used in both server and browser environments.这两个函数都可以在服务器和浏览器环境中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM