如何在 React 中打印组件?

Und*_*ned 1 javascript printing reactjs

我正在制作一个简单的简历生成应用程序。

索引.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);
Run Code Online (Sandbox Code Playgroud)

简历是从components/resume.js文件中生成的,它是一个功能组件..

我正在使用react-to-print库来单独打印简历组件。

也从这里参考..

但是在我的应用程序中,如果我单击Print Resume,则不会打印简历..

相反,我收到以下警告,

警告:不能为函数组件提供引用。尝试访问此引用将失败。你的意思是使用 React.forwardRef() 吗?

和另一个警告,

为了使“react-to-print”工作,只能打印基于类的组件。

完整的工作示例:

https://codesandbox.io/s/tailwind-react-sandbox-forked-uivc8

请尝试单击Print Resume上面链接中不打印简历的按钮。

你能帮我打印一下生成的简历吗?提前致谢..

hgb*_*123 6

你只需要使用 React.forwardRef()

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

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

分叉代码沙盒

编辑 Tailwind React Sandbox(分叉)