简体   繁体   中英

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.

The DOM tree isn't the active component but is instead available in a variable inside a function within the route.

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.

The final intent is to take the obj as a rendered blob and send it to a back end server for saving. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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