From 264699b4fa582a9477a467426b1790fd23a2ed8b Mon Sep 17 00:00:00 2001 From: colder Date: Sun, 14 Jun 2020 13:54:44 +0800 Subject: [PATCH] fix: textarea input event --- src/TextareaEnhance.tsx | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/TextareaEnhance.tsx b/src/TextareaEnhance.tsx index b17c7ae..7666e60 100644 --- a/src/TextareaEnhance.tsx +++ b/src/TextareaEnhance.tsx @@ -24,35 +24,39 @@ export interface TextareaEnhanceProps extends TextareaProps { export const TextareaEnhance: React.FC = (props) => { const { mergeChangeEvent = true, onInput, onBlur, onConfirm, ...rest } = props - const previousInputValue = useRef() + /** 上一个输入值 */ + const previousInputValue = useRef(props.value) const handleInput = useCallback( (e) => { + // 记录新值 previousInputValue.current = e.detail.value - onInput(e) + onInput && onInput(e) }, [onInput] ) const handleBlur = useCallback( (e) => { - if (mergeChangeEvent && e.detail.value !== previousInputValue.current) { + // 如果丢失焦点时的值与上一个值不同, 先触发 onInput + if (onInput && mergeChangeEvent && e.detail.value !== previousInputValue.current) { onInput({ ...e, detail: { ...e.detail, keyCode: 0 } }) } - onBlur(e) + onBlur && onBlur(e) }, - [onBlur, mergeChangeEvent] + [onInput, onBlur, mergeChangeEvent] ) const handleConfirm = useCallback( (e) => { - if (mergeChangeEvent && e.detail.value !== previousInputValue.current) { + // 如果点击"完成"绿按钮时的值与上一个值不同, 先触发 onInput + if (onInput && mergeChangeEvent && e.detail.value !== previousInputValue.current) { onInput({ ...e, detail: { ...e.detail, keyCode: 0, cursor: 0 } }) } - onConfirm(e) + onConfirm && onConfirm(e) }, - [onConfirm, mergeChangeEvent] + [onInput, onConfirm, mergeChangeEvent] ) - return