简体   繁体   English

有没有办法强制渲染 React 组件?

[英]Is there a way to render React components imperatively?

In a React application, I would like to render a DOM tree to a canvas or PDF.在 React 应用程序中,我想将 DOM 树渲染到 canvas 或 PDF。

The DOM tree isn't the active component but is instead available in a variable inside a function within the route. DOM 树不是活动组件,而是在路径内 function 内的变量中可用。

For example:例如:

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>
  )
}

Many libraries I have found such as html2canvas only allow imperative access to elements attached to the current document, alternatives like react-pdf require limited use of their components and won't allow me to use my components in the render step.我发现的许多库(例如html2canvas)只允许对附加到当前文档的元素进行强制访问,诸如react-pdf之类的替代方法需要对其组件的有限使用,并且不允许我在渲染步骤中使用我的组件。

The final intent is to take the obj as a rendered blob and send it to a back end server for saving.最终目的是将obj作为渲染的 blob 并将其发送到后端服务器进行保存。 This is then given to the user at a later date.然后在以后将其提供给用户。

Any help on this is much appreciated.非常感谢您对此的任何帮助。

I have an idea for you as before you capture your jsx element, you would put to the anchor in your active component, then you unmount it as you sent the snapshot to your backend:在您捕获 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>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM