How to print React component on click of a button?

前端 未结 8 2057
执念已碎
执念已碎 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;}
    }
    
    <h1 class = "no-printme"> do not print this </h1>    
    <div class='printme'>
      Print this only 
    </div>    
    <button onclick={window.print()}>Print only the above div</button>
    
    0 讨论(0)
  • 2020-12-03 02:18

    You'll have to style your printout with @media print {} in the CSS but the simple code is:

    export default class Component extends Component {
    
        print(){
            window.print();
        }
    
    
      render() {
    
      ...
      <span className="print"
                  onClick={this.print}>
        PRINT
        </span>
    
      } 
    }
    

    Hope that's helpful!

    0 讨论(0)
提交回复
热议问题