简体   繁体   中英

How to trigger this function on loading this React component, instead of requiring a button click?

So been trying to get this to work for a few days now, and am just not thinking of a solution. This is my first ReactJS project as I am more comfortable in C#.

Basically, I'm trying to create a print label component that will fire off the print dialog and print this printLabel component when the the link is clicked on the menu that calls this component. I can get this to work by having the component load in a drawer and mapping the trigger to an on-click event on a button, but I don't want the user to have to click an additional time.

import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';

class ComponentToPrint extends React.Component {
  render() {
    return (
      <Col>
         <Row>Customer Name</Row>
         <Row>Address</Row>
         <Row>City, State, Zip</Row>
      </Col>

    );
  }
}

const PrintLabel = () => {
  const componentRef = useRef();
  return (
    <div>
      <ReactToPrint
        trigger={() => <button>Print</button>}
        content={() => componentRef.current}
      />
      <ComponentToPrint ref={componentRef} />
    </div>
  );
};

export default PrintLabel;

It looks as though this behavior is not supported directly by react-to-print. One solution may be clicking the button (found by id) when the component renders. This can be done using the useEffect hook ( https://reactjs.org/docs/hooks-effect.html ).

import React, { useRef, useEffect } from 'react';

...

const PrintLabel = () => {
  const componentRef = useRef();

  useEffect(() => {
    document.getElementById('print-button').click();
  });

  return (
    <div>
      <ReactToPrint
        trigger={() => <button id="print-button">Print</button>}
        content={() => componentRef.current}
      />
      <ComponentToPrint ref={componentRef} />
    </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