renderProp.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { __assign } from "tslib";
  2. import * as React from 'react';
  3. import { useState, useCallback, useEffect, useLayoutEffect } from 'react';
  4. export function renderCar(WrappedComponent, defaults) {
  5. function State(_a) {
  6. var stateRef = _a.stateRef, props = _a.props;
  7. var renderTarget = useCallback(function SideTarget() {
  8. var args = [];
  9. for (var _i = 0; _i < arguments.length; _i++) {
  10. args[_i] = arguments[_i];
  11. }
  12. useLayoutEffect(function () {
  13. stateRef.current(args);
  14. });
  15. return null;
  16. }, []);
  17. // @ts-ignore
  18. return React.createElement(WrappedComponent, __assign({}, props, { children: renderTarget }));
  19. }
  20. var Children = React.memo(function (_a) {
  21. var stateRef = _a.stateRef, defaultState = _a.defaultState, children = _a.children;
  22. var _b = useState(defaultState.current), state = _b[0], setState = _b[1];
  23. useEffect(function () {
  24. stateRef.current = setState;
  25. }, []);
  26. return children.apply(void 0, state);
  27. }, function () { return true; });
  28. return function Combiner(props) {
  29. var defaultState = React.useRef(defaults(props));
  30. var ref = React.useRef(function (state) { return (defaultState.current = state); });
  31. return (React.createElement(React.Fragment, null,
  32. React.createElement(State, { stateRef: ref, props: props }),
  33. React.createElement(Children, { stateRef: ref, defaultState: defaultState, children: props.children })));
  34. };
  35. }