如何在加载此React组件时触发此功能,而不需要单击按钮?

问题描述 投票:0回答:1

因此,尝试将其工作几天已经开始了,只是没有考虑解决方案。这是我的第一个ReactJS项目,因为我更熟悉C#。

[基本上,我正在尝试创建一个打印标签组件,当在调用该组件的菜单上单击链接时,将触发打印对话框并打印此printLabel组件。我可以通过将组件加载到抽屉中并将触发器映射到按钮上的on-click事件来使其工作,但是我不希望用户不必再单击一次。

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

导出默认的PrintLabel;

javascript reactjs
1个回答
0
投票

看来反应到打印不直接支持此行为。一种解决方案是在渲染组件时单击按钮(按ID查找)。可以使用useEffect钩子(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>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.