0

I tried to call the printJS in react Component,but it didn't work when i clicked the button.Then I modified the code look like this.

 <button  onClick={printJS({printable:'docs/test.pdf',type:'pdf'})}>
                Print {this.state.type} with Message
 </button>

it works automatically when i first open the page but the click button is still invalid.

import React from 'react';
import printJS from 'print-js';


class PrintButton extends React.Component{

    constructor(props){
        super(props);
        this.state={
            name:'',
            type:'pdf',
        };
        this.handleNameChange=this.handleNameChange.bind(this);
        this.handleTypeChange=this.handleTypeChange.bind(this);
        this.print=this.print.bind(this);
    }

    handleNameChange(e){
        this.setState({name:e.target.value});
    }
    handleTypeChange(e){
        this.setState({type:e.target.value});
    }

    print(){
        let url;
        if(this.state.type==='pdf'){
            url=`docs/${this.state.name}`;
        }else if(this.state.type==='image'){
            url=`images/${this.state.name}`;
        }else if(this.state.type==='html'){
            url=`${this.state.name}`;
        }else{
            url=this.state.name;
        }
        printJS({printable:url,type:this.state.type});
    } 

    render(){
        return(
         <form>
            <label>
                选择类型:
                <select value={this.state.type} onChange={this.handleTypeChange}>
                <option value="pdf">PDF</option>
                <option value="image">IMAGE</option>
                <option value="html">HTML</option>
                <option value="json">JSON</option>
                </select>
            </label>
            <input value={this.state.name} type='text' onChange={this.handleNameChange}/>
            <button  onClick={this.print}>
                Print {this.state.type} with Message
            </button>
         </form>
        );

    }
}

export default PrintButton;

i want to design a printable react Component

潘夏开
  • 39
  • 4

1 Answers1

0

The problem seems to be that you have a button inside a form. As you are not specifying a type attribute for the button, the default value is submit:

submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.

Hence, when you click on the button you are submitting the form. You can avoid that by calling preventDefault on the click event:

 print(ev){
    let url;

    ev.preventDefault();

    if(this.state.type==='pdf'){
        url=`docs/${this.state.name}`;
    }else if(this.state.type==='image'){
        url=`images/${this.state.name}`;
    }else if(this.state.type==='html'){
        url=`${this.state.name}`;
    }else{
        url=this.state.name;
    }
    printJS({printable:url,type:this.state.type});
}
mgarcia
  • 5,669
  • 3
  • 16
  • 35