index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { useEvent, useState } from 'functional-mini/component';
  2. import '../_util/assert-component2';
  3. import { mountComponent } from '../_util/component';
  4. import { useComponentEvent } from '../_util/hooks/useComponentEvent';
  5. import useLayoutEffect from '../_util/hooks/useLayoutEffect';
  6. import { hasValue, useMergedState } from '../_util/hooks/useMergedState';
  7. import { triggerRefEvent } from '../_util/hooks/useReportRef';
  8. import { InputFunctionalProps } from './props';
  9. var Input = function (props) {
  10. var isControlled = hasValue(props.controlled)
  11. ? !!props.controlled
  12. : hasValue(props.value);
  13. var option = {
  14. value: props.value,
  15. };
  16. if (!isControlled && hasValue(props.value)) {
  17. option = {
  18. defaultValue: props.value,
  19. };
  20. }
  21. // 微信的 input 不支持受控模式
  22. // 通过 counter 的变化,重新渲染组件,让 value 改回去
  23. var _a = useState(0), counter = _a[0], setCounter = _a[1];
  24. var _b = useMergedState(props.defaultValue, option), value = _b[0], updateValue = _b[1];
  25. var _c = useState(false), selfFocus = _c[0], setSelfFocus = _c[1];
  26. var triggerEvent = useComponentEvent(props).triggerEvent;
  27. triggerRefEvent();
  28. useLayoutEffect(function (mount) {
  29. if (!isControlled && !mount) {
  30. updateValue(props.value);
  31. }
  32. }, [props.value]);
  33. useEvent('onChange', function (e) {
  34. var newValue = e.detail.value;
  35. if (!isControlled) {
  36. updateValue(newValue);
  37. }
  38. else {
  39. setCounter(function (c) { return c + 1; });
  40. }
  41. triggerEvent('change', newValue, e);
  42. });
  43. useEvent('onFocus', function (e) {
  44. var newValue = e.detail.value;
  45. setSelfFocus(true);
  46. triggerEvent('focus', newValue, e);
  47. });
  48. useEvent('onBlur', function (e) {
  49. var newValue = e.detail.value;
  50. setSelfFocus(false);
  51. triggerEvent('blur', newValue, e);
  52. });
  53. useEvent('onConfirm', function (e) {
  54. var newValue = e.detail.value;
  55. triggerEvent('confirm', newValue, e);
  56. });
  57. useEvent('onClear', function (e) {
  58. if (!isControlled) {
  59. updateValue('');
  60. }
  61. triggerEvent('change', '', e);
  62. });
  63. useEvent('update', function (e) {
  64. if (isControlled) {
  65. return;
  66. }
  67. updateValue(e);
  68. });
  69. return {
  70. counter: counter,
  71. state: {
  72. value: value,
  73. controlled: isControlled,
  74. },
  75. selfFocus: selfFocus,
  76. };
  77. };
  78. mountComponent(Input, InputFunctionalProps);