Skip to content

Commit d799d01

Browse files
committed
feat: support refs.
1 parent 8250634 commit d799d01

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

core/README.md

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,23 @@ npm install @uiw/react-signature
1414
```
1515

1616
```jsx mdx:preview
17-
import React from "react";
17+
import React, { useRef } from "react";
1818
import Signature from '@uiw/react-signature';
1919

2020
export default function App() {
21-
return <Signature />;
21+
const $svg = useRef(null);
22+
const handle = (evn) => {
23+
const parentElement = $svg.current
24+
while (parentElement.firstChild) {
25+
parentElement.removeChild(parentElement.firstChild);
26+
}
27+
}
28+
return (
29+
<>
30+
<Signature ref={$svg} />
31+
<button onClick={() => handle()}>Clear</button>
32+
</>
33+
);
2234
}
2335
```
2436

core/src/index.tsx

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useEffect, useRef } from 'react';
1+
import React, { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
22
import { getStroke, type StrokeOptions } from 'perfect-freehand';
33
import { getSvgPathFromStroke, getBoundingClientRect, getClinetXY, defaultOptions, defaultStyle } from './utils';
44

@@ -9,12 +9,14 @@ export interface SignatureProps extends React.SVGProps<SVGSVGElement> {
99

1010
let points: number[][] = [];
1111

12-
export default function Signature(props: SignatureProps = {}) {
12+
const Signature = forwardRef<SVGSVGElement, SignatureProps>((props, ref) => {
1313
const { className, prefixCls = 'w-signature', style, options, ...others } = props;
1414
const cls = [className, prefixCls].filter(Boolean).join(' ');
1515
const $svg = useRef<SVGSVGElement>(null);
1616
const $path = useRef<SVGPathElement>();
1717

18+
useImperativeHandle<SVGSVGElement | null, SVGSVGElement | null>(ref, () => $svg.current, [$svg.current]);
19+
1820
const handlePointerDown = (e: React.PointerEvent<SVGSVGElement>) => {
1921
const { offsetY, offsetX } = getBoundingClientRect($svg.current);
2022
const clientX = e.clientX || e.nativeEvent.clientX;
@@ -23,6 +25,7 @@ export default function Signature(props: SignatureProps = {}) {
2325
const pathElm = document.createElementNS('http://www.w3.org/2000/svg', 'path');
2426
$path.current = pathElm;
2527
$svg.current!.appendChild(pathElm);
28+
// $svg.current?.remove()
2629
};
2730

2831
const handlePointerMove = (e: PointerEvent) => {
@@ -59,4 +62,6 @@ export default function Signature(props: SignatureProps = {}) {
5962
style={{ ...defaultStyle, ...style }}
6063
/>
6164
);
62-
}
65+
});
66+
67+
export default Signature;

0 commit comments

Comments
 (0)