Skip to content

Commit

Permalink
chore: fixup ref usage
Browse files Browse the repository at this point in the history
  • Loading branch information
linbudu599 committed Jul 26, 2023
1 parent d41b6e1 commit 0831650
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions packages/appear/src/weex/index.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,34 @@
import type { ForwardedRef } from 'react';
import { useEffect, useRef, forwardRef, cloneElement, Children } from 'react';
import type { AppearProps } from '../typings';

const WeexAppear = forwardRef<any, AppearProps>((props, ref) => {
const childrenRef = ref || useRef<HTMLDivElement>(null);
const internalRef = useRef<HTMLDivElement>(null);
const childrenRef: ForwardedRef<HTMLDivElement> = ref ?? internalRef;

const { children, onAppear, onDisappear } = props;

useEffect(() => {
onAppear &&
typeof childrenRef === 'object' &&
childrenRef.current?.addEventListener('appear', (e: CustomEvent) => onAppear(e));
// Use copy of childrenRef to avoid ref value changed in cleanup phase.
const nodeRef = typeof childrenRef === 'object' ? childrenRef.current : null;

// Return early if onAppear callback not specified.
onAppear && nodeRef?.addEventListener('appear', (e: CustomEvent) => onAppear(e));

return () => {
onAppear &&
typeof childrenRef === 'object' &&
childrenRef.current?.removeEventListener('appear', (e: CustomEvent) => onAppear(e));
onAppear && nodeRef?.removeEventListener('appear', (e: CustomEvent) => onAppear(e));
};
}, []);
}, [childrenRef, onAppear]);

useEffect(() => {
onDisappear &&
typeof childrenRef === 'object' &&
childrenRef.current?.addEventListener('disappear', (e: CustomEvent) => onDisappear(e));
const nodeRef = typeof childrenRef === 'object' ? childrenRef.current : null;

onDisappear && nodeRef?.addEventListener('disappear', (e: CustomEvent) => onDisappear(e));

return () => {
onDisappear &&
typeof childrenRef === 'object' &&
childrenRef.current?.removeEventListener('disappear', (e: CustomEvent) => onDisappear(e));
onDisappear && nodeRef?.removeEventListener('disappear', (e: CustomEvent) => onDisappear(e));
};
}, []);
}, [childrenRef, onDisappear]);

return cloneElement(Children.only(children), { ref: childrenRef });
});
Expand Down

0 comments on commit 0831650

Please sign in to comment.