打印一个反应功能组件

Print a react functional component

大家好我已经开发了一个使用功能组件的反应应用程序,我需要在应用程序中打印特定页面。由于每个页面都是一个功能组件,我想也许我们可以单独打印一个组件。我尝试使用 react-to-print 但它仅支持 class 组件?这可以通过一些 NPM 包实现吗?

您可以将 react-to-print 与功能组件一起使用,如常见问题解答中所述。 这是他们在 npm 网站上使用的示例

import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';

import { ComponentToPrint } from './ComponentToPrint';

const Example = () => {
  const componentRef = useRef();

  return (
    <div>
      <ReactToPrint
        trigger={() => <button>Print this out!</button>}
        content={() => componentRef.current}
      />
      <ComponentToPrint ref={componentRef} />
    </div>
  );
};