【问题标题】:How to insert React component to HTML template?如何将 React 组件插入 HTML 模板?
【发布时间】:2021-09-15 15:16:48
【问题描述】:

我正在使用 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}
        />

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

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]。

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

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

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

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

    const yourString = renderToString(<YourComponent />);
    

    到那时,您可以使用yourString 作为字符串附加到您的渲染节点。

    【讨论】:

    • 完美!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2019-08-02
    • 2020-02-28
    • 1970-01-01
    • 2014-12-16
    相关资源
    最近更新 更多