How to print React component on click of a button?

前端 未结 8 2068
执念已碎
执念已碎 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:02

    Just sharing what worked in my case as someone else might find it useful. I have a modal and just wanted to print the body of the modal which could be several pages on paper.

    Other solutions I tried just printed one page and only what was on screen. Emil's accepted solution worked for me:

    https://stackoverflow.com/a/30137174/3123109

    This is what the component ended up looking like. It prints everything in the body of the modal.

    import React, { Component } from 'react';
    import {
        Button,
        Modal,
        ModalBody,
        ModalHeader
    } from 'reactstrap';
    
    export default class TestPrint extends Component{
        constructor(props) {
            super(props);
            this.state = {
                modal: false,
                data: [
                    'test', 'test', 'test', 'test', 'test', 'test', 
                    'test', 'test', 'test', 'test', 'test', 'test', 
                    'test', 'test', 'test', 'test', 'test', 'test',
                    'test', 'test', 'test', 'test', 'test', 'test',
                    'test', 'test', 'test', 'test', 'test', 'test',
                    'test', 'test', 'test', 'test', 'test', 'test',
                    'test', 'test', 'test', 'test', 'test', 'test',
                    'test', 'test', 'test', 'test', 'test', 'test'            
                ]
            }
            this.toggle = this.toggle.bind(this);
            this.print = this.print.bind(this);
        }
    
        print() {
            var content = document.getElementById('printarea');
            var pri = document.getElementById('ifmcontentstoprint').contentWindow;
            pri.document.open();
            pri.document.write(content.innerHTML);
            pri.document.close();
            pri.focus();
            pri.print();
        }
    
        renderContent() {
            var i = 0;
            return this.state.data.map((d) => {
                return (

    {i} - {d}

    ) }); } toggle() { this.setState({ modal: !this.state.modal }) } render() { return (
    Test Printing {this.renderContent()}
    ) } }

    Note: However, I am having difficulty getting styles to be reflected in the iframe.

提交回复
热议问题