react-native-navigation的迁移库

ComponentWrapper.tsx 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import * as React from 'react';
  2. import * as _ from 'lodash';
  3. import * as ReactLifecyclesCompat from 'react-lifecycles-compat';
  4. export class ComponentWrapper {
  5. static wrap(
  6. componentName: string,
  7. OriginalComponentClass: React.ComponentType<any>,
  8. store,
  9. componentEventsObserver): React.ComponentType<any> {
  10. class WrappedComponent extends React.Component<any, { componentId: string; allProps: {}; }> {
  11. static getDerivedStateFromProps(nextProps, prevState) {
  12. return {
  13. allProps: _.merge({}, nextProps, store.getPropsForId(prevState.componentId))
  14. };
  15. }
  16. constructor(props) {
  17. super(props);
  18. this._assertComponentId();
  19. this.state = {
  20. componentId: props.componentId,
  21. allProps: {}
  22. };
  23. }
  24. componentWillUnmount() {
  25. store.cleanId(this.state.componentId);
  26. componentEventsObserver.unmounted(this.state.componentId);
  27. }
  28. render() {
  29. return (
  30. <OriginalComponentClass
  31. {...this.state.allProps}
  32. componentId={this.state.componentId}
  33. key={this.state.componentId}
  34. />
  35. );
  36. }
  37. private _assertComponentId() {
  38. if (!this.props.componentId) {
  39. throw new Error(`Component ${componentName} does not have a componentId!`);
  40. }
  41. }
  42. }
  43. ReactLifecyclesCompat.polyfill(WrappedComponent);
  44. require('hoist-non-react-statics')(WrappedComponent, OriginalComponentClass);
  45. return WrappedComponent;
  46. }
  47. }