2023-05-06 15:49:37 +08:00
|
|
|
import * as React from 'react';
|
2020-02-03 13:00:35 +08:00
|
|
|
|
|
|
|
export default function usePatchElement(): [
|
|
|
|
React.ReactElement[],
|
2024-06-22 21:59:12 +08:00
|
|
|
(element: React.ReactElement) => () => void,
|
2020-02-03 13:00:35 +08:00
|
|
|
] {
|
|
|
|
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)
|
2022-11-19 13:47:33 +08:00
|
|
|
setElements((originElements) => [...originElements, element]);
|
2020-02-03 13:00:35 +08:00
|
|
|
|
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 () => {
|
2022-11-19 13:47:33 +08:00
|
|
|
setElements((originElements) => originElements.filter((ele) => ele !== element));
|
2020-02-03 13:00:35 +08:00
|
|
|
};
|
2020-12-02 20:00:31 +08:00
|
|
|
}, []);
|
2020-02-03 13:00:35 +08:00
|
|
|
|
|
|
|
return [elements, patchElement];
|
|
|
|
}
|