如何在React中打印一个组件?

3

我将制作一个简单的简历生成应用。

Index.js:

import ReactDOM from "react-dom";
import Resume from "../components/resume";
import React, { useRef } from "react";
import { useReactToPrint } from "react-to-print";

const App = () => {
  const componentRef = useRef();
  const handlePrint = useReactToPrint({
    content: () => componentRef.current
  });

  return (
    <div className="bg-gray-200 p-6">
      <button
        type="button"
        className="bg-gray-500 border border-gray-500 p-2 mb-4"
        onClick={handlePrint}
      >
        {" "}
        Print Resume{" "}
      </button>
      <Resume ref={componentRef} />
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

简介:简历是从components/resume.js文件生成的,它是一个函数式组件。我正在使用react-to-print库仅打印简历组件。还从这里参考了内容。但在我的应用程序中,如果我点击“打印简历”按钮,则无法打印简历。相反,我会得到以下警告:1. 功能组件无法获得引用。访问引用的尝试将失败。您是否打算使用React.forwardRef()?2. 要使“react-to-print”工作,只能打印基于类的组件。
要解决这个问题,请看一下完整的可行示例链接并单击“打印简历”按钮进行测试:https://codesandbox.io/s/tailwind-react-sandbox-forked-uivc8

你想将你的组件从基于函数转换为基于类吗? - elpmid
不,我需要将其作为功能组件单独存在。难道不能将其制作成功能组件吗? - Undefined
但是我只尝试过 https://www.npmjs.com/package/react-to-print#calling-from-functional-components-with-usereacttoprint 这个与函数组件有关的。 - Undefined
好的,我明白了,我试一下。 - elpmid
2个回答

11

你只需要使用React.forwardRef()

const Resume = React.forwardRef((props, ref) => {
  // ...

  return (
    <div className="bg-gray-200 p-6" ref={ref}>
      ...
    </div>
  )
})

分叉的codesandbox

编辑Tailwind React Sandbox(派生)


2

您想要打印的组件仍然需要是一个类组件,因此我将 Resume 组件转换为了类组件。

如果您尝试使用这个引用来打印 <h1 ref={componentRef}>HELLO?</h1>,即使简单的 h1 标签不是基于类的组件,也会起作用。

在您编辑的沙盒上尝试一下。

如果您想要一个稳定的函数式组件,您可以将 Resume 组件迁移到 <div ref={componentRef} /> 的子组件中。


2
它在功能组件本身中运行。感谢您的尝试和帮助。 - Undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接