【问题标题】:How to use react-to-print with TypeScript?如何在 TypeScript 中使用 react-to-print?
【发布时间】:2020-04-03 23:57:27
【问题描述】:

我通常使用 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} />

要创建引用,我只需这样做:

const componentRef = useRef();

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

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

【问题讨论】:

  • 你安装了@types/react 包吗?

标签: reactjs typescript react-to-print


【解决方案1】:

你可以定义useRef的类型来摆脱ts错误credit to shane935:

const componentRef = useRef<HTMLDivElement>(null)

如果你像我一样使用函数式组件,你会在尝试使用基于 react-to-print 类的组件之后的 ref 时遇到问题。要绕过此错误,您可以将要打印的组件包装在 div 中:

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

这个div里面的所有东西都会被打印出来。

【讨论】:

    【解决方案2】:

    使用钩子时似乎是一个已知问题: 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

    【讨论】:

      猜你喜欢
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 2022-10-15
      • 1970-01-01
      • 2022-10-20
      • 2019-06-27
      • 2014-04-30
      相关资源
      最近更新 更多