baseComponent.tsx 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * The Semi Foundation / Adapter architecture split was inspired by Material Component For Web. (https://github.com/material-components/material-components-web)
  3. * We re-implemented our own code based on the principle and added more functions we need according to actual needs.
  4. */
  5. import React, { Component } from 'react';
  6. import log from '@douyinfe/semi-foundation/utils/log';
  7. import { DefaultAdapter } from '@douyinfe/semi-foundation/base/foundation';
  8. import { VALIDATE_STATUS } from '@douyinfe/semi-foundation/base/constants';
  9. import { ArrayElement } from './base';
  10. const { hasOwnProperty } = Object.prototype;
  11. export type ValidateStatus = ArrayElement<typeof VALIDATE_STATUS>;
  12. export interface BaseProps {
  13. style?: React.CSSProperties;
  14. className?: string;
  15. }
  16. // eslint-disable-next-line
  17. export default class BaseComponent<P extends BaseProps = {}, S = {}> extends Component<P, S> {
  18. static propTypes = {};
  19. static defaultProps = {};
  20. cache: any;
  21. foundation: any;
  22. constructor(props: P) {
  23. super(props);
  24. this.cache = {};
  25. this.foundation = null;
  26. }
  27. componentDidMount(): void {
  28. this.foundation && typeof this.foundation.init === 'function' && this.foundation.init();
  29. }
  30. componentWillUnmount(): void {
  31. this.foundation && typeof this.foundation.destroy === 'function' && this.foundation.destroy();
  32. this.cache = {};
  33. }
  34. get adapter(): DefaultAdapter<P, S> { // eslint-disable-line
  35. return {
  36. getContext: key => { // eslint-disable-line
  37. if (this.context && key) {
  38. return this.context[key];
  39. }
  40. },
  41. getContexts: () => this.context, // eslint-disable-line
  42. getProp: key => this.props[key], // eslint-disable-line
  43. // return all props
  44. getProps: () => this.props, // eslint-disable-line
  45. getState: key => this.state[key], // eslint-disable-line
  46. getStates: () => this.state, // eslint-disable-line
  47. setState: (states, cb) => this.setState({ ...states }, cb), // eslint-disable-line
  48. getCache: key => key && this.cache[key], // eslint-disable-line
  49. getCaches: () => this.cache, // eslint-disable-line
  50. setCache: (key, value) => key && (this.cache[key] = value), // eslint-disable-line
  51. stopPropagation: e => { // eslint-disable-line
  52. try {
  53. e.stopPropagation();
  54. e.nativeEvent && e.nativeEvent.stopImmediatePropagation();
  55. } catch (error) {
  56. }
  57. }
  58. };
  59. }
  60. // eslint-disable-next-line
  61. isControlled = (key: any) => Boolean(key && this.props && typeof this.props === 'object' && hasOwnProperty.call(this.props, key));
  62. log(text: string, ...rest: any): any {
  63. return log(text, ...rest);
  64. }
  65. }