【问题标题】:Is there a way to render React components imperatively?有没有办法强制渲染 React 组件?
【发布时间】:2023-03-29 15:35:01
【问题描述】:

在 React 应用程序中,我想将 DOM 树渲染到画布或 PDF。

DOM 树不是活动组件,而是在路由内函数内的变量中可用。

例如:

import React from 'react';
import axios from 'axios';

function Summary(props) {

  function SaveForm(){
    const obj = <div>I am what is saved</div>
    const obj_as_blob = ...code to save obj as canvas/pdf/blob...
    axios.post('/save',obj_as_blob)
      .then((resp)=>{console.log(resp)})
  }

  return (
    <div>
      <p>I am what the user sees</p>
      <button onClick={SaveForm}>Send File to backend</button>
    </div>
  )
}

我发现的许多库(例如 html2canvas)只允许对附加到当前文档的元素进行强制访问,诸如 react-pdf 之类的替代方法需要限制使用它们的组件,并且不允许我在渲染步骤中使用我的组件.

最终目的是将obj 作为渲染的blob,并将其发送到后端服务器进行保存。然后在以后将其提供给用户。

非常感谢您对此的任何帮助。

【问题讨论】:

  • 你不知道查询特定DOM的代码放在哪里转换?
  • @tmhao2005 想象一下,他们将有一个提交按钮,当他们提交时,我会将&lt;div&gt;I am what is saved&lt;/div&gt; 异步呈现为 pdf 并通过 HTTP POST 将其发送到后端服务器。
  • 说实话,我并没有完全让你好起来。这是在您单击按钮进行转换 + 提交文件时调用的回调吗?
  • @tmhao2005 我已经通过示例进行了更改,这有帮助吗?
  • 你不能把它渲染成一个隐藏的html然后保存它的内容吗?

标签: javascript reactjs


【解决方案1】:

我有一个想法,就像在您捕获 jsx 元素之前一样,您将放置在活动组件中的锚点,然后在将快照发送到后端时卸载它:

function Summary(props) {

  const yourAnchor = React.useRef();


  function save() {
    const obj = <div>I am what is saved</div>;

    ReactDOM.render(obj, yourAnchor.target, () => {
      // your jsx finally attached to the document
      const obj_as_blob = ...code to save obj as canvas/pdf/blob...

      axios.post('/save',obj_as_blob)
       .finally(() => {
         // Unmount the node
         ReactDOM.unmountComponentAtNode(yourAnchor.current);
       })
    });
  }

  return (
    <div>
      <div ref={yourAnchor} />
      <p>I am what the user sees</p>
      <button onClick={save}>Send File to backend</button>
    </div>
  )
}

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 2018-07-03
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2018-10-11
    • 2016-08-01
    • 2021-11-18
    • 2021-03-05
    相关资源
    最近更新 更多