๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๋‚ด๊ฐ€ ๋งŒ๋‚œ ERROR

[React] e.preventDefault();

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 11. 16.
๋ฐ˜์‘ํ˜•

๐Ÿช“ ์ˆ˜์ • ์ „ ์ฝ”๋“œ

writeComment = e => {
  this.setState({
    comment: e.target.value,
  });
};

addComment = e => {
 โญ๏ธ e.preventDefault();
    const { commentList, comment } = this.state;
    this.setState({
      commentList: [
        ...commentList,
        {
          id: commentList.length + 1,
          userName: 'zzz_yk',
          content: comment,
        },
      ],
      comment: '',
    });
  };

  enterKey = e => {
    if (e.key === 'Enter') {
      this.addComment();
    }
  };
<div className="reply">
  <input
    type="text"
    id="input"
    value={comment}
    placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..."
    onChange={this.writeComment}
    onKeyPress={this.enterKey}
  />
  <button
    type="button"
    className="reply-btn"
    onClick={this.addComment}
  >
  ๊ฒŒ์‹œ
  </button>
</div>

 

 

์ด๋ ‡๊ฒŒ ํ•˜๊ณ  ๋Œ“๊ธ€์„ ์“ฐ๊ณ  Enter๋ฅผ ์น˜๋ฉด!!

์ด๋Ÿฐ ๋ฉ”์„ธ์ง€๊ฐ€ ๋œฌ๋‹ค!!!ใ… ใ… 

 

 

๊ทธ๋ž˜์„œ <input>์— onkeyPress๋ฅผ ์—†์• ๊ณ  input ํƒœ๊ทธ๋ฅผ <form> ํƒœ๊ทธ๋กœ ๊ฐ์‹ธ์ฃผ์—ˆ๋‹ค!

 

๐Ÿ”ฅ e.preventDefault()๋กœ submit ์ด๋ฒคํŠธ ๋ฐœ์ƒ์‹œ reload ์•ˆํ•˜๊ธฐ

html์—์„œ a ํƒœ๊ทธ๋‚˜ submit ํƒœ๊ทธ๋Š” ๊ณ ์œ ์˜ ๋™์ž‘์œผ๋กœ ํŽ˜์ด์ง€๋ฅผ ์ด๋™์‹œํ‚ค๊ฑฐ๋‚˜, form ์•ˆ์— input ๋“ฑ์„ ์ „์†กํ•˜๋Š” ๋™์ž‘์ด ์žˆ๋Š”๋ฐ e.preventDefault()๋Š” ๊ทธ ๋™์ž‘์„ ์ค‘์ง€์‹œํ‚ค๋Š” ์—ญํ• ์„ ํ•œ๋‹ค.
<input> ๋˜๋Š” <button> ํด๋ฆญ ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ ํŽ˜์ด์ง€๊ฐ€ reload ๋˜๋Š”๋ฐ, ๊ทธ ํ˜„์ƒ์„ ๋ง‰์•„์คŒ!!!
์ฐธ๊ณ ๐Ÿ‘‰๐Ÿป event.preventDefault

 

 

 

๐Ÿช“ ์ˆ˜์ • ํ›„ ์ฝ”๋“œ

writeComment = e => {
  this.setState({
    comment: e.target.value,
  });
};

addComment = e => {
  e.preventDefault();
  const { commentList, comment } = this.state;
  this.setState({
    commentList: [
      ...commentList,
      {
        id: commentList.length + 1,
        userName: 'zzz_yk',
        content: comment,
      },
    ],
    comment: '',   
  });
};

  // enterKey = e => {
  //   if (e.key === 'Enter') {
  //     this.addComment();
  //   }
  // };
<div className="reply">
  <form onSubmit={this.addComment}>
    <input
      type="text"
      id="input"
      value={comment}
      placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..."
      onChange={this.writeComment}
    />
  </form>
  <button
    type="button"
    className="reply-btn"
    onClick={this.addComment}
  >
  ๊ฒŒ์‹œ
  </button>
</div>


์ € preventDefault(); ๊ฐ€ ์—†์œผ๋ฉด... ๋Œ“๊ธ€์„ ์ž…๋ ฅํ•˜๋ฉด ๋ฐ”๋กœ reload๊ฐ€ ๋˜๋ฒ„๋ฆผ!!!
์ž˜ ๋‚˜์˜ค๋Š”๊ตฌ๋งŒ...ํํํ

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€