2020-02-03 13:00:35 +08:00
|
|
|
import * as React from 'react';
|
|
|
|
|
|
|
|
export default function usePatchElement(): [
|
|
|
|
React.ReactElement[],
|
|
|
|
(element: React.ReactElement) => Function,
|
|
|
|
] {
|
|
|
|
const [elements, setElements] = React.useState<React.ReactElement[]>([]);
|
|
|
|
|
2020-12-02 20:00:31 +08:00
|
|
|
const patchElement = React.useCallback((element: React.ReactElement) => {
|
2020-07-15 19:51:56 +08:00
|
|
|
// append a new element to elements (and create a new ref)
|
2020-02-03 13:00:35 +08:00
|
|
|
setElements(originElements => [...originElements, element]);
|
|
|
|
|
2020-07-15 19:51:56 +08:00
|
|
|
// return a function that removes the new element out of elements (and create a new ref)
|
|
|
|
// it works a little like useEffect
|
2020-02-03 13:00:35 +08:00
|
|
|
return () => {
|
|
|
|
setElements(originElements => originElements.filter(ele => ele !== element));
|
|
|
|
};
|
2020-12-02 20:00:31 +08:00
|
|
|
}, []);
|
2020-02-03 13:00:35 +08:00
|
|
|
|
|
|
|
return [elements, patchElement];
|
|
|
|
}
|