reactComponent.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var __assign = (this && this.__assign) || function () {
  2. __assign = Object.assign || function(t) {
  3. for (var s, i = 1, n = arguments.length; i < n; i++) {
  4. s = arguments[i];
  5. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  6. t[p] = s[p];
  7. }
  8. return t;
  9. };
  10. return __assign.apply(this, arguments);
  11. };
  12. import * as React from 'react';
  13. import { Injector } from '@wendellhu/redi';
  14. import { RediProvider, RediConsumer } from './reactContext';
  15. function RediInjector(props) {
  16. var children = props.children, dependencies = props.dependencies;
  17. var childInjectorRef = React.useRef(null);
  18. // dispose the injector when the container Injector unmounts
  19. React.useEffect(function () { return function () { var _a; return (_a = childInjectorRef.current) === null || _a === void 0 ? void 0 : _a.dispose(); }; }, []);
  20. return (React.createElement(RediConsumer, null, function (context) {
  21. var childInjector;
  22. if (childInjectorRef.current) {
  23. childInjector = childInjectorRef.current;
  24. }
  25. else {
  26. childInjector = context.injector
  27. ? context.injector.createChild(dependencies)
  28. : new Injector(dependencies);
  29. childInjectorRef.current = childInjector;
  30. }
  31. return (React.createElement(RediProvider, { value: { injector: childInjector } }, children));
  32. }));
  33. }
  34. /**
  35. * @param Comp
  36. * @param injector
  37. * @returns
  38. */
  39. export function connectInjector(Comp, injector) {
  40. return function ComponentWithInjector(props) {
  41. return (React.createElement(RediProvider, { value: { injector: injector } },
  42. React.createElement(Comp, __assign({}, props))));
  43. };
  44. }
  45. export function connectDependencies(Comp, dependencies) {
  46. return function ComponentWithInjector(props) {
  47. return (React.createElement(RediInjector, { dependencies: dependencies },
  48. React.createElement(Comp, __assign({}, props))));
  49. };
  50. }
  51. //# sourceMappingURL=reactComponent.js.map