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

This commit is contained in:
Irie Aoi 2020-12-12 19:31:51 +09:00
parent 7bcf48c8bf
commit 5c0aea50d7
1 changed files with 10 additions and 4 deletions

View File

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