【问题标题】:How can I print an page with react-to-print如何使用 react-to-print 打印页面
【发布时间】:2021-02-16 13:26:46
【问题描述】:

我的表单上需要一个打印按钮。我正在为一个图书馆做一项研究,我发现了这个:

https://www.npmjs.com/package/react-to-print

我在考虑这个流程:一个组件导入并在我的代码中添加一行来调用该组件,打印按钮效果很好,但据我了解,这个组件需要我传递要完整打印的组件.

我试图这样做,但我得到了这个错误:

  Attempted import error: './index' does not contain a standard export (imported as 'FormContent').

我的索引代码:

const App = () => {
    let numb_days = 22
    return (
        <div className="m-4">
            <FormField label="Salário Base" show_small_text="false" numb_days={ numb_days }/>
            <hr />
            <h6 className="mb-4"> Qtd. dias úteis: { numb_days } </h6>
            <FormField label="Auxilio Refeição" show_small_text="true" numb_days={ numb_days }/>
            <FormField label="Auxilio Alimentação" show_small_text="true" numb_days={ numb_days }/>
            <FormField label="Plano de Saúde" show_small_text="false" numb_days={ numb_days }/>
            <FormField label="Outros Benefìcios (VT)" show_small_text="true" numb_days={ numb_days }/>
            <ComponentToPrint ref={(el) => (this.componentRef = el)} />
        </div>
    );
};

我的组件代码:

import React, { Component } from "react";
import FormContent from "./index";

class ComponentToPrint extends Component {
  render() {
    return <FormContent ref={(el) => (this.componentRef = el)} />;
  }
}

export default ComponentToPrint;

我想我一定是犯了一个大错误,但我不明白我将如何将我的索引传递给这个组件并同时调用我的索引。

我找到了这个例子:https://codesandbox.io/s/interesting-cookies-k1bg9?file=/src/deliverySheet/ComponentToPrint.js

看来我需要顺其自然:

index -> print (my content).

但是为什么我不能这样做呢? ->

index -> my content (print)

或

index -> my content AND print

【问题讨论】:

    标签: javascript reactjs react-to-print


    【解决方案1】:

    我不确定我是否理解您的问题,但我会尝试回答,由于所有子文件夹,您提供的示例真的很难阅读。基本上,要打印对打印做出反应,您需要做的是制作一个普通组件并在同一级别上引用它。 我看到你使用类组件,所以我只是从 react-to-print 文档中复制和粘贴。

    import React from 'react';
    import ReactToPrint from 'react-to-print';
    
    import { ComponentToPrint } from './ComponentToPrint';
    
    class Example extends React.PureComponent {
      render() {
        return (
          <div>
            <ReactToPrint
              trigger={() => {
                // NOTE: could just as easily return <SomeComponent />. Do NOT pass an `onClick` prop
                // to the root node of the returned component as it will be overwritten.
                return <a href="#">Print this out!</a>;
              }}
              content={() => this.componentRef}
            />
            <ComponentToPrint ref={el => (this.componentRef = el)} />
          </div>
        );
      }
    }
    

    上面写着“触发器”的地方就是你渲染按钮的地方。 我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 2022-10-15
      • 2020-03-30
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-20
      相关资源
      最近更新 更多