index.js 2.5 KB

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