React 두번 째

SSO·2022년 1월 30일
0

react_opentutorial

목록 보기
2/3

### 1. 이벤트 생성

React에서 이벤트를 처리하는 방법

Example

<button onClick={}>
	----
</button>

→ on 뒤에 대문자로 시작한다!

그 외의 차이점

  • false를 반환해도 기본 동작을 방지할 수 없다. → preventDefault()를 호출해야 링크의 기본 동작을 방지할 수 있다.(새로고침x)

Example

<header>
   <h1><a href="/" onClick={function(e){
      e.preventDefault();
      this.props.onChangePage(); //props로 전달된 함수 호출
    }.bind(this)}>{this.props.title}</a></h1>
    {this.props.sub}
</header>
  • e : 합성 이벤트
  • bind(this) : 콜백에서 this가 작동하기 위해 사용.

2. Form

: 사용자가 폼을 제출하면 새로운 페이지로 이동하는 기본 HTML폼 동작을 수행한다.

React에서는 JavaScript함수로 폼의 제출을 처리하고 사용자가 입력한 데이터에 접근하도록 하는 것이 편리하다.(제어 컴포넌트 방식)

  • 제어 컴포넌트란? → 사용자 입력값을 제어하는 방식으로 React에 의해 값이 제어되는 입력 폼 element.
  • setState() → state의 값을 바꾸기 위해서 사용해야 하는 함수. 이렇게 하면 안돼!! this.state.mode = 'welcome' this.setState({mode:'welcome'}) 이게 정답! constructor내에서는 자유롭게 변경 가능하다.

3. Create 구현

Create버튼을 누르면 새로운 내용을 추가할 수 있는 폼을 만들어보자.

  • TOC에 해당하는 content에 새로 추가한 내용이 반영되어야 한다.

CreateContent.js (일부 생략)

render(){
      return(
        <article>
          <h2>Create</h2>
          <form acrion="/create_process" method="post"
            onSubmit={function(e){
              e.preventDefault();
              this.props.onSubmit(
							//title과 desc의 값을 이벤트에 넘겨줌
                e.target.title.value,
                e.target.desc.value 
              );
            }.bind(this)}
          >
					// 입력하는 칸 구현
            <p>
              <input 
                type="text" 
                name="title" 
                placeholder="title"
              ></input>
            </p>
            <p>
              <textarea name="desc" placeholder="description"></textarea>
            </p>
            <p>
              <input type="submit"></input>

placeholder : 미리보기랄까? 텍스트를 입력하는 칸에 무엇을 입력해야하는지 연하게 쓰여 있음.

App.js 일부

<form acrion="/create_process" method="post"
   onSubmit={function(e){
     e.preventDefault();
     this.props.onSubmit(
        e.target.title.value,
        e.target.desc.value
      );
    }.bind(this)}
 >
   <p><input type="text" name="title" 
    placeholder="title"></input></p>
   <p>
     <textarea name="desc" placeholder="description"></textarea>
   </p>
    <p>
      <input type="submit"></input>
    </p>
</form>
  • state내에 새로운 내용을 추가하고자 한다면?? → concat을 사용하자! concat은 원본을 변경하지 않는다. 하지만 push의 경우 원본을 변경하기 때문에 프로그램이 커지면 번거로워진다.
  • 만약 push를 사용한다면?
    • Immutable
      push를 사용하면서 원본이 변하지 않는 것을 원한다면 Array.from을 사용하자.
      단, 배열의 경우에만 사용 가능.
      객체에서는 Object.assign()을 사용하면 된다.
  • ShouldComponentUpdate(newProps, newState) → render함수가 실행될 지 말 지 결정하는 함수.
    return 값을 false로 줄 경우 맨 처음 render함수 실행 후
    그 이후로는 render가 호출되지 않음
    return 값을 true로 주면 두 함수 모두 계속 실행 newProps, newState
    : 바뀐 props와 state의 값을 의미
    바뀌기 이전 값에도 접근 가능

code 관련은 프로그램 참고!!

profile
👩🏻‍💻👊🏻⭐️

0개의 댓글