How to print React component on click of a button?

前端 未结 8 2061
执念已碎
执念已碎 2020-12-03 01:42

How can I print only one component on click of a button.

I know this solution:

window.frames[\"print_frame\"].window.focus();
window.frames[\"print         


        
8条回答
  •  遥遥无期
    2020-12-03 02:16

    The solution provided by Emil Ingerslev is working fine, but CSS is not applied to the output. Here I found a good solution given by Andrewlimaza. It prints the contents of a given div, as it uses the window object's print method, the CSS is not lost. And there is no need for an extra iframe also.

    var printContents = document.getElementById("divcontents").innerHTML;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
    

    Update 1: There is unusual behavior, in chrome/firefox/opera/edge, the print or other buttons stopped working after the execution of this code.

    Update 2: The solution given is there on the above link in comments:

    .printme { display: none;}
    @media print { 
        .no-printme  { display: none;}
        .printme  { display: block;}
    }
    
    

    do not print this

    Print this only

提交回复
热议问题