[TIL] input value clear ๐Ÿ˜‚

imimยท2022๋…„ 5์›” 11์ผ
0

ref๋กœ HTML ์—˜๋ฆฌ๋จผํŠธ์— ์ ‘๊ทผ/์ œ์–ดํ•˜๊ธฐ

๐Ÿ”ผ ์ถœ๋ฐœ์€ ์ด ์ •๋„์˜€์œผ๋‚˜..
Input ์ปดํฌ๋„ŒํŠธ ๋‚ด์—์„œ value ๋ฅผ props.value ๊ฐ’๊ณผ onChange ๋ฅผ ํ†ตํ•ด ๊ด€๋ฆฌํ•˜๋‹ค ๋ณด๋‹ˆ, ์Šคํฌ๋ฆฝํŠธ๋กœ inputRef.current.value ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ์œผ๋กœ๋Š” change ์ด๋ฒคํŠธ๊ฐ€ ํŠธ๋ฆฌ๊ฑฐ ๋˜์ง€ ์•Š์•˜๋‹ค. ๐Ÿ’ฅ


React onChange ์ด๋ฒคํŠธ ๊ฐ•์ œ๋กœ ๋ฐœ์ƒ์‹œํ‚ค๊ธฐ

  • ๊ฒ€์ƒ‰์–ด: inputRef dispatchevent change
  • dispatchEvent change on select element cannot be handled by delegate | stack overflow

    ์ด๋ฒคํŠธ๊ฐ€ ์ „ํŒŒ๋˜๋„๋ก ๋ช…์‹œ์ ์œผ๋กœ ์ง€์ •ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
    ์ด๋ฒคํŠธ ์ „ํŒŒ์—ฌ๋ถ€ bubbles์˜ ๊ธฐ๋ณธ๊ฐ’์€ false์ด๊ธฐ ๋•Œ๋ฌธ์—, ์œ„์ž„์„ ๋ฐ›์€ ํ•ธ๋“ค๋Ÿฌ๊ฐ€ change ์ด๋ฒคํŠธ๋ฅผ ์ˆ˜์‹ ํ•˜์ง€ ๋ชปํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ”ผ ๊ทธ๋Ÿฌ๋‚˜ ๋‚˜์˜ ๊ฒฝ์šฐ์—๋Š” dispatchevent ์ธ์ž๋กœ change ์ด๋ฒคํŠธ๋กœ๋Š” ์›ํ•˜๋Š”๋Œ€๋กœ ๋™์ž‘ํ•˜์ง€ ์•Š์•˜๊ณ  input ์ด๋ฒคํŠธ๋ฅผ ์ถ”๊ฐ€ํ•ด์„œ ์‚ฌ์šฉํ•ด์•ผ ๋น„๋กœ์†Œ ๋™์ž‘ํ–ˆ๋‹ค. ๐Ÿ’ฅ

How do I programmatically trigger an โ€œinputโ€ event without jQuery?

๐Ÿ”— ํ•จ๊ป˜ ์ฝ์„๊ฑฐ๋ฆฌ



๊ฒฐ๊ณผ code

const clearInput = (e) => {
  const ev = new Event('input', { bubbles: true });
  inputRef.current.value = '';
  inputRef.current.dispatchEvent(ev);
};

const handleMouseDown = (e) => e.preventDefault();

<Button
  onClick={clearInput}
  onMouseDown={handleMouseDown}
/>

0๊ฐœ์˜ ๋Œ“๊ธ€