react-native-navigation的迁移库

ComponentWrapper.tsx 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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(componentName: string, OriginalComponentClass: React.ComponentType<any>, store): React.ComponentType<any> {
  6. class WrappedComponent extends React.Component<any, { componentId: string; allProps: {}; }> {
  7. static getDerivedStateFromProps(nextProps, prevState) {
  8. return {
  9. allProps: _.merge({}, nextProps, store.getPropsForId(prevState.componentId))
  10. };
  11. }
  12. private originalComponentRef;
  13. constructor(props) {
  14. super(props);
  15. this._assertComponentId();
  16. this._saveComponentRef = this._saveComponentRef.bind(this);
  17. this.state = {
  18. componentId: props.componentId,
  19. allProps: {}
  20. };
  21. }
  22. componentDidMount() {
  23. store.setRefForId(this.state.componentId, this);
  24. }
  25. componentWillUnmount() {
  26. store.cleanId(this.state.componentId);
  27. }
  28. componentDidAppear() {
  29. if (this.originalComponentRef.componentDidAppear) {
  30. this.originalComponentRef.componentDidAppear();
  31. }
  32. }
  33. componentDidDisappear() {
  34. if (this.originalComponentRef.componentDidDisappear) {
  35. this.originalComponentRef.componentDidDisappear();
  36. }
  37. }
  38. onNavigationButtonPressed(buttonId) {
  39. if (this.originalComponentRef.onNavigationButtonPressed) {
  40. this.originalComponentRef.onNavigationButtonPressed(buttonId);
  41. }
  42. }
  43. onSearchBarUpdated(text, isFocused) {
  44. if (this.originalComponentRef.onSearchBarUpdated) {
  45. this.originalComponentRef.onSearchBarUpdated(text, isFocused);
  46. }
  47. }
  48. render() {
  49. return (
  50. <OriginalComponentClass
  51. ref={this._saveComponentRef}
  52. {...this.state.allProps}
  53. componentId={this.state.componentId}
  54. key={this.state.componentId}
  55. />
  56. );
  57. }
  58. private _assertComponentId() {
  59. if (!this.props.componentId) {
  60. throw new Error(`Component ${componentName} does not have a componentId!`);
  61. }
  62. }
  63. private _saveComponentRef(r) {
  64. this.originalComponentRef = r;
  65. }
  66. }
  67. ReactLifecyclesCompat.polyfill(WrappedComponent);
  68. require('hoist-non-react-statics')(WrappedComponent, OriginalComponentClass);
  69. return WrappedComponent;
  70. }
  71. }