如何将 React-to-Print 与 TypeScript 结合使用?

Axe*_*eón 10 typescript reactjs react-to-print

我通常使用react-to-print(https://www.npmjs.com/package/react-to-print)来打印React组件,既省力又灵活。我开始使用 TypeScript 编写应用程序,这是我第一次需要将这两件事结合起来。

这是我的代码:

<ReactToPrint
  trigger={() => <Button variant="contained" color="primary">Generar</Button>}
  content={() => componentRef.current}
/>
<PrintableComponent ref={componentRef} />
Run Code Online (Sandbox Code Playgroud)

要创建参考,我只需执行以下操作:

const componentRef = useRef();
Run Code Online (Sandbox Code Playgroud)

在 JavaScript 中,它可以工作,但是当我使用时.tsx,我在 ReactToPrint 组件的“content”参数中收到一个错误,在我自己的 PrintableComponent 的 ref 参数中收到另一个错误。有人可以帮我解决这个问题吗?

基本上,错误表明接口不匹配。

tin*_*ike 13

您可以定义 useRef 的类型来消除 ts 错误归功于 Shane935

const componentRef = useRef<HTMLDivElement>(null)
Run Code Online (Sandbox Code Playgroud)

如果您像我一样正在使用功能组件,那么在尝试使用基于反应打印类的组件之后的引用时,您会遇到问题。要绕过此错误,您可以将要打印的组件包装在 div 中:

<ReactToPrint
  trigger={() => <Button variant="contained" color="primary">Generar</Button>}
  content={() => componentRef.current}
/>
<div ref={componentRef}>
  <PrintableComponent />
</div>
Run Code Online (Sandbox Code Playgroud)

该 div 内的所有内容都将被打印。


小智 4

使用挂钩时似乎是一个已知问题: https ://github.com/gregnb/react-to-print/issues/214

作为替代方案,您可以避免useRef挂钩并按照源存储库中的示例进行操作,该示例似乎可以在 TypeScript 中工作:

https://github.com/gregnb/react-to-print/blob/master/example/index.tsx

即,npm 自述文件中的第一个示例: https://www.npmjs.com/package/react-to-print#example