如何将 SignaturePad 与 React TypeScript 一起使用

How to use SignaturePad with React TypeScript

我正在尝试在我的 React 项目中实现 SignaturePad,我可以绘制签名,但我无法访问属性以清除或保存它。我在 ref={signCanvas} 以及 current.clear() 和 signCanvas.current.clear() 和 signCanvas.getTrimmedCanvas().toDataURL("image/png" 上收到以下错误)

没有与此调用匹配的重载。

  Overload 1 of 2, '(props: Readonly<ReactSignatureCanvasProps>): ReactSignatureCanvas', gave the following error.
    Type 'MutableRefObject<{}>' is not assignable to type 'string | ((instance: ReactSignatureCanvas | null) => void) | RefObject<ReactSignatureCanvas> | null | undefined'.
      Type 'MutableRefObject<{}>' is not assignable to type 'RefObject<ReactSignatureCanvas>'.
        Types of property 'current' are incompatible.
          Type '{}' is missing the following properties from type 'ReactSignatureCanvas': on, off, clear, isEmpty, and 14 more.
  Overload 2 of 2, '(props: ReactSignatureCanvasProps, context?: any): ReactSignatureCanvas', gave the following error.
    Type 'MutableRefObject<{}>' is not assignable to type 'string | ((instance: ReactSignatureCanvas | null) => void) | RefObject<ReactSignatureCanvas> | null | undefined'.
      Type 'MutableRefObject<{}>' is not assignable to type 'RefObject<ReactSignatureCanvas>'.ts(2769)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ReactSignatureCanvas> & Readonly<ReactSignatureCanvasProps> & Readonly<...>'
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ReactSignatureCanvas> & Readonly<ReactSignatureCanvasProps> & Readonly<...>'*

这是我目前所实施的,任何帮助将不胜感激。

const signCanvas = useRef({});

const clear = () => signCanvas.current.clear();
const save = () => console.log(signCanvas.getTrimmedCanvas().toDataURL("image/png"));

<SignaturePad
 ref={signCanvas}
 canvasProps={{ className: "signature__canvas" }}
/>

<Button color='grey' content='Clear' onClick={clear} />
<Button color='grey' content='Save' onClick={save} />

我设法解决了这个问题。如果有人有同样的问题,只需要为 React.MutableRefObject

添加以下内容
const signCanvas = React.useRef() as React.MutableRefObject<any>;

现在后续工作正常。

 const clear = () => signCanvas.current.clear();

 const save = () =>
 console.log(signCanvas.current.getTrimmedCanvas().toDataURL("image/png"));