Skip to content

Commit

Permalink
输入法状态不触发onChange的input组件
Browse files Browse the repository at this point in the history
  • Loading branch information
YSMJ1994 committed Dec 17, 2019
1 parent 32ac8f1 commit c716ed8
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/components/NoCompositionInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React, { RefForwardingComponent, InputHTMLAttributes, useState, useEffect, forwardRef } from 'react';

interface RequiredProps {
value: number | string;
onChange: (value: number | string) => any;
}

const NoCompositionInput: RefForwardingComponent<
HTMLInputElement,
Merge<InputHTMLAttributes<HTMLInputElement>, RequiredProps>
> = ({ value, onChange, ...otherProps }, ref) => {
const [inputValue, setInputValue] = useState(value);
const [isComposition, setIsComposition] = useState<boolean>(false);
useEffect(() => {
setInputValue(value);
}, [value]);
useEffect(() => {
!isComposition && onChange && onChange(inputValue);
}, [isComposition, inputValue]);
return (
<input
ref={ref}
{...otherProps}
value={inputValue}
onCompositionStart={() => setIsComposition(true)}
onCompositionUpdate={() => setIsComposition(true)}
onCompositionEnd={() => setIsComposition(false)}
onChange={e => {
const value = e.target.value;
setInputValue(value);
}}
/>
);
};
const Input = forwardRef(NoCompositionInput);
export default Input;

0 comments on commit c716ed8

Please sign in to comment.