如何将 SignaturePad 与 React TypeScript 一起使用
Posted
技术标签:
【中文标题】如何将 SignaturePad 与 React TypeScript 一起使用【英文标题】:How to use SignaturePad with React TypeScript 【发布时间】:2020-12-11 08:51:07 【问题描述】:我正在尝试在我的 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 />
【问题讨论】:
【参考方案1】:我设法解决了这个问题。如果有人有同样的问题,只需为 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"));
【讨论】:
以上是关于如何将 SignaturePad 与 React TypeScript 一起使用的主要内容,如果未能解决你的问题,请参考以下文章
Angular2-signaturepad 与 Angular 一起使用会导致找不到模块错误
将 Angular 2 签名板 JSON 转换为 jQuery.signaturePad JSON
SignaturePad 手写画板使用 & 背景未覆盖canvas问题