버튼 클릭을 요구하는 대신이 React 컴포넌트를로드 할 때이 함수를 트리거하는 방법은 무엇입니까?

저스틴 블레인 브리지

그래서 며칠 동안 이것을 작동 시키려고 노력하고 있으며 해결책을 생각하고 있지 않습니다. 이것은 C #에 더 익숙한 첫 번째 ReactJS 프로젝트입니다.

기본적으로 인쇄 대화 상자를 시작하고이 구성 요소를 호출하는 메뉴에서 링크를 클릭하면이 printLabel 구성 요소를 인쇄하는 인쇄 레이블 구성 요소를 만들려고합니다. 서랍에 구성 요소를로드하고 트리거를 버튼의 클릭시 이벤트에 매핑하여이 작업을 수행 할 수 있지만 사용자가 추가 시간을 클릭 할 필요는 없습니다.

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 내보내기;

에드 루카스

이 동작은 react-to-print에서 직접 지원되지 않는 것처럼 보입니다. 한 가지 해결책은 구성 요소가 렌더링 될 때 버튼 (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>
  );
};

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사