调用打印功能后页面冻结

时间:2019-01-22 11:10:07

标签: javascript reactjs

我正在使用window.print()函数来打印div的内容,但是当我调用print函数时,整个页面会冻结。请参见下面的代码:

render(){
  return(
   <div>
    <div className='style' id='divToPrint'>
     <p>Content to print here.</p>
     <p>Content to print here.</p>
     <p>Content to print here.</p>
   </div>
    <button className='someStyle' onClick={() => printDiv('divToPrint')}>Print</button
    <button className='someStyle' onClick={this.somethingElse}>Something Else
</button>
  </div>
 )
}

打印功能:

function printDiv(divName) {
  let printContents = document.getElementById(divName).innerHTML;
  let originalContents = document.body.innerHTML;

  document.body.innerHTML = printContents;

  window.print();

  document.body.innerHTML = originalContents;
}

打印并调用document.body.innerHTML = originalContents之后,在刷新页面之前,我无法执行其他任何操作。整个页面冻结了。

我想念什么吗?

1 个答案:

答案 0 :(得分:0)

您可以将内容保存在state中,也可以将其保存在props中并显示

class MyComponent extends React.Component {
state = {
  content:''
}
printDiv = (content) => {
  this.setState({content})
}
render() {
  const {content} = this.state;
  return (
   <div>
    <p>{content}</p>
    <button className='someStyle' onClick={() => printDiv('divToPrint')}>Print</button>
   </div>
 )
}