2015-05-09 84 views
5

如何在點擊按鈕時只打印一個組件。如何點擊按鈕打印React組件?

我知道這個解決方案:

window.frames["print_frame"].window.focus(); 
window.frames["print_frame"].window.print(); 
$('.print_frame').remove(); 

他們的反應並不想用一個框架來工作。

任何解決方案?謝謝。

回答

12

客戶端上有兩種解決方案。一個是像你發佈的框架。您可以使用,雖然一個iframe:

var content = document.getElementById("divcontents"); 
var pri = document.getElementById("ifmcontentstoprint").contentWindow; 
pri.document.open(); 
pri.document.write(content.innerHTML); 
pri.document.close(); 
pri.focus(); 
pri.print(); 

這預計這個網站存在

<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe> 

另一個解決方案是使用介質選擇和對media="print"樣式隱藏一切你不想打印。

<style type="text/css" media="print"> 
    .no-print { display: none; } 
</style> 

最後一路在服務器上需要一些工作。您可以將所有HTML + CSS發送到服務器,並使用許多組件之一來生成可打印的文檔,如PDF。我已經嘗試過使用PhantomJs做這個設置。

+0

我檢查它是因爲我現在使用它。但這不是一個好的解決方案,因爲它會在大多數瀏覽器(Firefox和Chrome)中被阻止,因爲它的行爲像一個彈出窗口。 – AndryName

+0

我不確定我的理解。我提到的解決方案都不會觸發彈出式窗口攔截器。使用CSS,不會,使用現有的iframe不會和使用服務器方法絕對不會。你能解釋一下你的意思嗎? –

+0

http://www3.govst.edu/webct/webct6/student/popups/step2.gif – AndryName

3

我認爲這會比結果更復雜。你必須在CSS的,但簡單的代碼media @print {}風格你打印的是:

export default class Component extends Component { 
 

 
    print(){ 
 
    window.print(); 
 
    } 
 
    
 
    
 
    render() { 
 
    
 
    ... 
 
    <span className="print" 
 
       onClick={this.print}> 
 
    PRINT 
 
    </span> 
 
    
 
    } 
 
    
 
}

希望這是有幫助!

2

如果您打算打印您已有權訪問的特定數據,無論是來自Store,AJAX還是其他地方,都可以使用我的庫反應打印。

https://github.com/captray/react-print

它使創建打印模板更容易(假設你已經有反應的依賴)。你只需要適當地標記你的HTML。

此ID應該添加到實際DOM樹中較高的位置以排除除下面的「打印裝載」之外的所有內容。

<div id="react-no-print"> 

這是你的反應,打印組件將安裝和包裝你的模板創建:

<div id="print-mount"></div> 

一個例子看起來是這樣的:

var PrintTemplate = require('react-print'); 
var ReactDOM = require('react-dom'); 
var React = require('react'); 

var MyTemplate = React.createClass({ 
    render() { 
     return (
      <PrintTemplate> 
       <p>Your custom</p> 
       <span>print stuff goes</span> 
       <h1>Here</h1> 
      </PrintTemplate> 
     ); 
    } 
}); 

ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount')); 

值得一提的是,您可以在模板內創建新的或使用現有的子組件,並且所有內容都應該適合打印。

+0

可以請提供給我們演示網址.. –

+0

這應該證明它。只需按Ctrl + P打印即可看結果窗口。 https://jsfiddle.net/captray/69z2wepo/68966/ – captray

0

2017年6月19日這對我來說很完美。

import React, {Component} from 'react' 


class PrintThisComponent extends Component { 

    componentDidMount() { 

    console.log('PrintThisComponent mounted!') 

    } 

    render() { 

    return (
     <div> 

     <button onClick={() => window.print()}>PRINT</button> 

     <p>Click above button opens print preview with these words on page</p> 

     </div> 

    ) 
    } 
} 

export default PrintThisComponent 
+2

雖然此代碼可能會回答問題,但提供有關如何解決問題和/或解決問題原因的其他上下文會提高答案的長期價值。 – thewaywewere