我通常使用React (https://www.npmjs.com/package/react-to-print)来打印反应组件,这是一种低工作量和很大的灵活性。我开始用TypeScript编写我的应用程序,这是我第一次需要将这两件事结合起来。
这是我的密码:
<ReactToPrint
  trigger={() => <Button variant="contained" color="primary">Generar</Button>}
  content={() => componentRef.current}
/>
<PrintableComponent ref={componentRef} />要创建引用,我只需:
const componentRef = useRef();在JavaScript中,它可以工作,但是当我使用.tsx时,我在ReactToPrint组件的"content“参数中出现了一个错误,在我自己的PrintableComponent的ref参数中出现了另一个错误。有人能帮我吗?
基本上,错误说接口不匹配。
发布于 2020-04-04 01:10:04
在使用钩子时,似乎是一个已知的问题: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
发布于 2021-05-03 12:38:57
您可以为useRef定义类型以消除ts错误贷给shane935。
const componentRef = useRef<HTMLDivElement>(null)如果你,像我一样,使用功能组件,你会遇到一个问题,试图使用下面的ref基于类的反应类组件。若要绕过此错误,可以将希望打印的组件包装在div中:
<ReactToPrint
  trigger={() => <Button variant="contained" color="primary">Generar</Button>}
  content={() => componentRef.current}
/>
<div ref={componentRef}>
  <PrintableComponent />
</div>这个div里面的所有东西都会被打印出来。
https://stackoverflow.com/questions/61022107
复制相似问题