getConfigureItem.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import React, { useCallback, useEffect } from 'react';
  2. import { Context } from './context';
  3. import { get } from 'lodash';
  4. import cls from 'classnames';
  5. interface ConfigureItemOpts {
  6. valueKey?: string;
  7. onKeyChangeFnName?: string;
  8. valuePath?: string;
  9. className?: string;
  10. defaultProps?: Record<string, any>
  11. }
  12. function getConfigureItem(Component: any, opts: ConfigureItemOpts = {}) {
  13. const ConfigureItem = (props: any) => {
  14. const { field, onChange: onOriginChange, className, ...rest } = props;
  15. const {
  16. valueKey = 'value',
  17. onKeyChangeFnName = 'onChange',
  18. valuePath,
  19. className: optsCls,
  20. defaultProps = {}
  21. } = opts;
  22. const { value = {}, onChange, onRemove } = React.useContext(Context);
  23. const onItemChange = useCallback(
  24. (value: any) => {
  25. const valueResult = valuePath ? get(value, valuePath) : value;
  26. onChange({ [field]: valueResult });
  27. onOriginChange?.(valueResult);
  28. },
  29. [field, onChange, onOriginChange, valuePath],
  30. );
  31. // 用于处理初始值的注册
  32. // Registration for handling initial values
  33. useEffect(() => {
  34. const { initValue } = props;
  35. initValue !== undefined && onChange({ [field]: props.initValue }, true);
  36. return () => {
  37. onRemove(field);
  38. };
  39. }, []);
  40. const valueProps = {
  41. [valueKey]: value[field],
  42. [onKeyChangeFnName]: onItemChange,
  43. };
  44. return <Component className={cls({
  45. [className]: className,
  46. [optsCls]: optsCls,
  47. })} {...defaultProps} {...rest} {...valueProps} />;
  48. };
  49. return ConfigureItem;
  50. }
  51. export default getConfigureItem;