有没有一种方法可以强制地渲染React组件?

时间:2020-07-29 03:21:29

标签: javascript reactjs

在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,并将其发送到后端服务器进行保存。然后将其提供给用户。

在此方面的任何帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

我为您提供了一个想法,因为在捕获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>
  )
}