baseComponent.tsx 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import React, { Component } from 'react';
  2. import log from '@douyinfe/semi-foundation/utils/log';
  3. import { DefaultAdapter } from '@douyinfe/semi-foundation/base/foundation';
  4. import { VALIDATE_STATUS } from '@douyinfe/semi-foundation/base/constants';
  5. import { ArrayElement } from './base';
  6. const { hasOwnProperty } = Object.prototype;
  7. export type ValidateStatus = ArrayElement<typeof VALIDATE_STATUS>;
  8. export interface BaseProps {
  9. style?: React.CSSProperties;
  10. className?: string;
  11. }
  12. // eslint-disable-next-line
  13. export default class BaseComponent<P extends BaseProps = {}, S = {}> extends Component<P, S> {
  14. static propTypes = {};
  15. static defaultProps = {};
  16. cache: any;
  17. foundation: any;
  18. constructor(props: P) {
  19. super(props);
  20. this.cache = {};
  21. this.foundation = null;
  22. }
  23. componentDidMount(): void {
  24. this.foundation && typeof this.foundation.init === 'function' && this.foundation.init();
  25. }
  26. componentWillUnmount(): void {
  27. this.foundation && typeof this.foundation.destroy === 'function' && this.foundation.destroy();
  28. this.cache = {};
  29. }
  30. get adapter(): DefaultAdapter<P, S> { // eslint-disable-line
  31. return {
  32. getContext: key => { // eslint-disable-line
  33. if (this.context && key) {
  34. return this.context[key];
  35. }
  36. },
  37. getContexts: () => this.context, // eslint-disable-line
  38. getProp: key => this.props[key], // eslint-disable-line
  39. // return all props
  40. getProps: () => this.props, // eslint-disable-line
  41. getState: key => this.state[key], // eslint-disable-line
  42. getStates: () => this.state, // eslint-disable-line
  43. setState: (states, cb) => this.setState({ ...states }, cb), // eslint-disable-line
  44. getCache: key => key && this.cache[key], // eslint-disable-line
  45. getCaches: () => this.cache, // eslint-disable-line
  46. setCache: (key, value) => key && (this.cache[key] = value), // eslint-disable-line
  47. stopPropagation: e => { // eslint-disable-line
  48. try {
  49. e.stopPropagation();
  50. e.nativeEvent && e.nativeEvent.stopImmediatePropagation();
  51. } catch (error) {
  52. }
  53. }
  54. };
  55. }
  56. // eslint-disable-next-line
  57. isControlled = (key: any) => Boolean(key && this.props && typeof this.props === 'object' && hasOwnProperty.call(this.props, key));
  58. log(text: string, ...rest: any): any {
  59. return log(text, ...rest);
  60. }
  61. }