如何将 React 组件插入 HTML 模板?

How to insert React component to HTML template?

我正在使用 React-treeviz 依赖项来做出反应,以便在我的应用程序中创建 Tree 组件。我想在我的树节点中使用 React 组件,例如 material-ui 图标。

我的树组件:

<TreevizReact
          data={data_1}
          relationnalField={"father"}
          nodeWidth={120}
          nodeHeight={80}
          areaHeight={500}
          areaWidth={1000}
          mainAxisNodeSpacing={2}
          secondaryAxisNodeSpacing={2}
          linkShape={"quadraticBeziers"}
          renderNode={(data) => {
            const nodeData = data.data;
            const settings = data.settings;
            let result = "";
            if (data.depth !== 2) {
              result = `<div class="box" style='cursor:pointer;height:${settings.nodeHeight}px; width:${settings.nodeWidth}px;display:flex;flex-direction:column;justify-content:center;align-items:center;background-color:${nodeData.color};border-radius:5px;'><div><strong>
          ${nodeData.text_1}
          </strong>
          
          </div><div>is</div><div><i>
          ${nodeData.text_2}
          </i></div></div>`;
            } else {
              result = `<div class="box" style='cursor:pointer;height:${
                settings.nodeHeight
              }px; width:${
                settings.nodeHeight
              }px;display:flex;flex-direction:column;justify-content:center;align-items:center;background-color:${
                nodeData.color
              };border-radius:${settings.nodeHeight / 2}px;'><div><strong>
          ${nodeData.text_1}
          </strong></div></div>`;
            }
            return result;
          }}
          duration={600}
          isHorizontal
          linkWidth={(node) => 10}
        />

你可以看到它有一个 renderNode 属性 那个 returns html 模板: (为简单起见,我删除了样式)

renderNode={(data) => {
let result = "";
result = `<div>
<strong>
   ${nodeData.text_1}
</strong>
</div>`
return result;
}

我试图在此模板中插入一个组件,例如:

renderNode={(data) => {
let result = "";
result = `<div>
<strong>
   ${nodeData.text_1}
</strong>
${<Icon/>}
</div>`
return result;
}

但是我得到的结果是[Object object]。

此代码框 link 中提供了示例代码:https://codesandbox.io/s/lingering-browser-iiqud?file=/src/App.js

在您的应用程序上显示它有点复杂,但我在这里做了一个简单的例子供您参考

基本上,您需要使用 react-dom/server 中的 renderToString 将其呈现为字符串。

const yourString = renderToString(<YourComponent />);

届时,您可以使用 yourString 作为字符串附加到您的 renderNode。