タグ入力欄からフォーカスが外れた時文字があるならタグとして確定させる

This commit is contained in:
Irie Aoi 2020-12-12 19:31:51 +09:00
parent 7bcf48c8bf
commit 5c0aea50d7

View File

@ -23,8 +23,7 @@ export const TagInput: React.FC<TagInputProps> = ({ id, name, values, isInvalid,
case 'Enter':
case ' ':
if ((event as any).isComposing !== true) {
onChange && onChange(values.concat(buffer.trim().replace(/\s+/g, '_')));
setBuffer('');
commitBuffer();
}
event.preventDefault();
break;
@ -32,8 +31,7 @@ export const TagInput: React.FC<TagInputProps> = ({ id, name, values, isInvalid,
// 実際にテキストボックスに入力されている文字を見に行く (フォールバック処理)
const nativeEvent = event.nativeEvent;
if (nativeEvent.srcElement && (nativeEvent.srcElement as HTMLInputElement).value.slice(-1) == ' ') {
onChange && onChange(values.concat(buffer.trim().replace(/\s+/g, '_')));
setBuffer('');
commitBuffer();
event.preventDefault();
}
break;
@ -45,6 +43,13 @@ export const TagInput: React.FC<TagInputProps> = ({ id, name, values, isInvalid,
}
};
const commitBuffer = () => {
const newTag = buffer.trim().replace(/\s+/g, '_');
if (newTag.length === 0) return;
onChange && onChange(values.concat(newTag));
setBuffer('');
};
return (
<div className={containerClass} onClick={() => inputRef.current?.focus()}>
<input name={name} type="hidden" value={values.join(' ')} />
@ -66,6 +71,7 @@ export const TagInput: React.FC<TagInputProps> = ({ id, name, values, isInvalid,
className="tis-tag-input-field"
value={buffer}
onChange={(e) => setBuffer(e.target.value)}
onBlur={commitBuffer}
onKeyDown={onKeyDown}
/>
</li>