[React] React 웹앱 - CREATE

soheeoott·2021년 4월 2일
0

React

목록 보기
4/7

📌 참고 📌

https://www.youtube.com/watch?v=nwwJ2xU7E8w&list=PLuHgQVnccGMCRv6f8H9K5Xwsdyg4sFSdi&index=28

함수를 호출하여 인자 값을 전달하는 방법

App.js : 상위 컴포넌트

<Control onChangeMode={function(_mode){

Control.js : 하위 컴포넌트

// 함수를 호출하여 인자 값을 전달
this.props.onChangeMode('create');

조건문을 사용하여 컴포넌트 출력

App.js : 상위 컴포넌트

render(){
  let _title, _desc, _article = null;
  _article = <CreateContent></CreateContent> // 조건에 충족하면
} return (
  {_article}
);

onSubmit 이벤트

App.js : 상위 컴포넌트

_article = <CreateContent onSubmit={function(_title, _desc){
  // _title : e.target.title.value
  // _desc : e.target.desc.value
}.bind(this)}></CreateContent>

CreateContent.js : 하위 컴포넌트

<form onSubmit={function(e){
  e.preventDefault();
  
  // 상위 컴포넌트의 onSubmit() 함수를 호출
  this.props.onSubmit(
    // _title, _desc 인자 값 전달
    e.target.title.value,
    e.target.desc.value
  );
}.bind(this)}>
  
// name="title" : e.target.title.value
// name="desc" : e.target.desc.value
<input type="text" name="title" placeholder="title"></input>
<textarea name="desc" placeholder="desc"></textarea>

새로운 값을 마지막 값으로 추가

App.js : 상위 컴포넌트

constructor(props){
  super(props);
  // 불필요한 렌더링 방지를 위해 maxId 을 state 밖에 생성
  // 마지막 this.state.contents.id 값과 동일
  // 새로운 값을 push 할 때 사용하는 데이터
  this.maxId = 3;
  // this.state
}
render() {
  if(this.state.mode === 'create'){
    _article = <CreateContent onSubmit={function(_title, _desc){
      // this.maxId = 3 id 값+1
      this.maxId = this.maxId+1;

      // concat 
      // : 불변성(immutable) = 원본의 값을 변경하지 않는다. 
      // : 원본을 변경한 새로운 리턴한 값을 변수에 담아 사용
      // ex) let arr = [1,2];
      //     let result = arr.concat(3); [1, 2, 3];
      let _contents = this.state.contents.concat(
        {id:this.maxId, title:_title, desc:_desc})

      this.setState({
        contents:_contents
      });
    }.bind(this)}></CreateContent>
  }
}
profile
📚 글쓰는 습관 들이기 📚

0개의 댓글