首页 > 解决方案 > 如何在地图函数中将 React 组件转换为字符串或 HTML?

问题描述

如何在地图函数中将 React 组件转换为字符串或 HTML?

我正在开发一个在 SSR(服务器端渲染)架构中构建的项目。我对 React / Node 架构相对较新,我知道我需要重构我的代码以遵循良好的实践。但就目前而言,我正在尝试以我更好理解的方式做事。

这是基本场景:

我正在研究一个映射数组的子组件:

(一些代码)

import ReactDOMServer from "react-dom/server";
import FrontendContent from "./frontend-content-cb-component.js";

(一些代码)

在渲染方法中,总结起来,我有这样的事情:

render(){
    return(
        { arrPublicationsListing.map((publicationsRow, publicationsRowKey) =>{
            return (
                <FrontendContent key={publicationsRowKey} 
                      idParentContent={ publicationsRow.id } 
                      idTbContent={ "" } 
                      contentType={ 3 } 
                      configLayoutType={ 2 } 
                      configContentNRecords={ "" } 
                      configContentSort={ "" }>
                </FrontendContent>
            );
       })}
   );
}

到目前为止,这正在按预期工作。问题是我需要将内容从成为一个字符串,因为我要对它做点什么。注意:是一个复杂的组件,它执行一些 API 获取等。但在此设置中工作正常。

因此,我进行了一些研究并尝试了这种方式:

render(){
    return(
        { arrPublicationsListing.map((publicationsRow, publicationsRowKey) =>{
            return (
                { ReactDOMServer.renderToString(<FrontendContent key={publicationsRowKey} 
                      idParentContent={ publicationsRow.id } 
                      idTbContent={ "" } 
                      contentType={ 3 } 
                      configLayoutType={ 2 } 
                      configContentNRecords={ "" } 
                      configContentSort={ "" }>
                 </FrontendContent>) }
            );
       })}
   );
}

它没有渲染并返回一个奇怪的错误。关于我如何做到这一点的任何想法?我应该尝试另一种方法吗?我想坚持在渲染返回中进行迭代的想法。

谢谢,

标签: javascriptnode.jsreactjsserver-side-rendering

解决方案


推荐阅读