javascript - 调用打印函数后页面卡住

标签 javascript reactjs

我正在使用 window.print() 函数来打印 div 的内容,但是当我调用打印函数时整个页面都卡住了。请看下面的代码:

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 后,在刷新页面之前我无法执行任何其他操作。整个页面都卡住了。

我是不是漏了什么?

最佳答案

可以将内容保存在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>
 )
}

关于javascript - 调用打印函数后页面卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54306986/

相关文章:

javascript - AngularJS ngTable延迟显示ajax数据

javascript - 将 JavaScript NPM 项目与 Spring Boot 融合

javascript - 如何防止 onInput 在动态组件初始化期间触发?

javascript - 使用路由路由器 v4 强制更新相同的路由

javascript - React.js 增量和减量计数器未正确映射

javascript - 使用 javascript 函数在 MVC 中设置模型属性

javascript - 在 Javascript 中将 é 转换为其原始形式

javascript - Owl Carousel 在滑动到第三个元素时隐藏第二个元素

javascript - 正确地将参数传递给 react 方法

javascript - 在 react redux 中重定向之前如何等待操作完成?