거북이개발자

[React] create, updeat, delete 구현 본문

React/React

[React] create, updeat, delete 구현

류정식 2021. 1. 16. 16:37

1. 목표

리액트를 활용하는 공부.

특히

  • create
  • update
  • delete

을 중점적으로  본다.

 

2. 결과

 

위의 사진처럼

create : 새로운 제목과 내용을 삽입한다.

update: 기존의 내용을 수정한다.

delete : 선택된 값을 삭제한다.

 

이렇게 3가지를 구현할 것 이다.

 


3-1. 깨달은 점(Create)

1.

<Control onChangeMode={function(_mode){
this.setState({
          mode:_mode
        });
        }
        }.bind(this)}

이런식으로 creat를 만들 표시해준다. 이때 onChangeMode를 props로 보낸다.

 

2.

    <li><a href="/crete" onClick={function(e){
         
         e.preventDefault();
          this.props.onChangeMode('create');
        }.bind(this)}>crete</a></li>
        

 

이렇게 onChangeMode를 props로 받고  onClick를 이용하여 클릭시 모드를 create로 변경하도록한다.

 

3.

 this.max_content_id=this.max_content_id+1;
         
       var _content=Array.from(this.state.contents);
        _content.push({id: this.max_content_id, title:_title, desc:_desc});
      

 

Array.from은 원본을 보존하면서 새로운 복사본을 만든다. 그후 새받은 인자의 값을 푸쉬 해준다.

 

4.

<article>      
            <h2>create</h2>
         <form action="/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>

         </article>

 

이부부은 CreateContent.js의 일부분인데 흥미로운 부부분은 <form> 의 어트리뷰트로 onSubmit이 있다는 점이고

action, method 속성도 알아 두어야 한다.

또한 this.props.onSubmit와 onSubmit는 다른 메소드이다.

 

3-2. 깨달은 점(Update)

1.

class UpdateContent extends Component{
    

  
  constructor(props){
      super(props);
      this.state={
        id:this.props.data.id,
        title:this.props.data.title,
        desc:this.props.data.desc
      }
      this.inputFormHandler= this.inputFormHandler.bind(this);
    }

    inputFormHandler(e){
      this.setState({[e.target.name] : e.target.value});
    }
  
  
  
    render(){
      return(

        
        <article>      
            <h2>Update</h2>
         <form action="/Update_process" method="post"
          onSubmit={function(e){
            e.preventDefault();
            
            this.props.onSubmit(this.state.id, this.state.title, this.state.desc);
            
          }.bind(this)}
         >

          <input type="hidden" name="id" value={this.state.id}></input>
          <p><input type="text" name="title" placeholder="title" value={this.state.title} onChange={this.inputFormHandler}></input></p>
          <p><textarea name="desc" placeholder="description" value={this.state.desc} onChange={this.inputFormHandler}></textarea></p>
          <p><input type="submit"></input></p>
         </form>

         </article>

    
      );
    }
  }

 

우선 속성data로 받아온 값을 state로 설정해준다.

onChange를 통해 입력받은 값을 변경할 수 있다.

여기서 inputFormHandler 함수가 중요하다.

 

 

2.

 

else if(this.state.mode ==='update'){
    
      _content=this.getReadContent();
      _article=<UpdateContent 
        data={_content} 
        onSubmit={
              function(_id, _title, _desc){
              var _contents=Array.from(this.state.contents);
                var i=0;
                while(i<_contents.length){
                if(_contents[i].id===_id){
                  _contents[i]={id:_id, title:_title, desc:_desc};
                  break;
                }
                  i=i+1;

                }
                this.setState({
                contents:_contents,
                mode:'read'
                });
      }.bind(this)}></UpdateContent>
    }

 

create랑 비슷하다. 다만  id가 동일한 컨텐츠의 값을 변경해준다.

 

 

 

3-3. 깨달은 점(Delete)

1.

        if(_mode==='delete'){
          if(window.confirm('really delete?')){
            var _contents=Array.from(this.state.contents); 
            var i=0;
             while(i<this.state.contents.length){
               if(_contents[i].id===this.state.selected_content_id){
                 _contents.splice(i,1);
                 break;
               }
              
              i=i+1;
             }
             this.setState({
               mode:'welcome',
              contents:_contents
            });
          }
        }

delete는 비교적 간단하다.

.splice함수를 이용하여 제거 할 수 있다.

Comments