본문 바로가기
Programming/Javascript

React기초- 8.Update

by Wilkyway 2020. 7. 29.
반응형

업데이트하는 방법에 대해 알아보겠습니다. 업데이트는 기존의 contents를 불러와서 보여주는 read 기능과 form의 형태로 다시 입력하는 create 기능이 결합된 기능이라고 할 수 있습니다.

 

1. UpdateContent.js

import React, { Component } from 'react';

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);   // bind를 construct에서 구현하여 추후 계속 bind를 물고가는 부분을 제거
    }
    inputFormHandler(e) {
        this.setState({ [e.target.name]: e.target.value }); // target name값에 따라 input / textarea 를 각각 업데이트함
    }
    render() {
        return (
            <div>
                <article>
                    <h2>Update</h2>
                    <form action="/create_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>   {/* id와 같이 사용자에게 보여줄 필요 없는 부분 */}
                        {/* onChange는 필요 없음. 현재 프로그래밍의 기조임 */}
                        <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>
            </div>
        );
    }
}

export default UpdateContent;

 

2. App.js

import React, { Component } from 'react';
import Subject from './components/Subject';
import TOC from './components/TOC';
import ReadContent from './components/ReadContent';
import CreateContent from './components/CreateContent';
import UpdateContent from './components/UpdateContent'; // 신규 컴포넌트 추가
import Control from './components/Control';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.max_content_id = 3;
    this.state = {
      mode: 'create',
      selected_content_id: 2,
      welcome: { title: 'welcom', desc: 'Hello, React!!' },
      subject: { title: 'WEB', sub: 'world wide web!' },
      contents: [
        { id: 1, title: 'HTML', desc: 'HTML is HyperText ...' },
        { id: 2, title: 'CSS', desc: 'CSS is for design' },
        { id: 3, title: 'Javascript', desc: 'JavaScript is for interactive' }
      ]
    }
  }

  getReadContent() {  //selected_content_id 와 일치하는 content를 찾는 부분만 별도로 작성 ->read / update에서 같이 사용
    var i = 0;
    while (i < this.state.contents.length) {
      var data = this.state.contents[i];
      if (data.id === this.state.selected_content_id) {
        return data;
        break;
      }
      i = i + 1;
    }
  }
  //  render 함수를 새로운 함수로 분리
  getContent() {
    var _title, _desc, _article = null;
    if (this.state.mode === 'welcome') {
      _title = this.state.welcome.title;
      _desc = this.state.welcome.desc;
      _article = <ReadContent title={_title} desc={_desc}></ReadContent>
    } else if (this.state.mode === 'read') {
      var _content = this.getReadContent();         //getReadContent()로부터 data 형태로 값을 받음
      _article = <ReadContent title={_content.title} desc={_content.desc}></ReadContent>  // data형태의 값인 _content로부터 title 과 desc를 참조함
    } else if (this.state.mode === 'create') {
      _article = <CreateContent onSubmit={function (_title, _desc) {
        this.max_content_id = this.max_content_id + 1;
        var _contents = Array.from(this.state.contents)
        _contents.push({ id: this.max_content_id, title: _title, desc: _desc })
        this.setState({
          contents: _contents,
          mode: 'read',  // 수정한 다음에는 자동으로 read모드가 되도록
          selected_content_id: this.max_content_id // 선택된 값은 마지막 값이 되도록
        })
      }.bind(this)}></CreateContent>
    } else if (this.state.mode === 'update') { // update 모드 구현
      _content = this.getReadContent();
      _article = <UpdateContent data={_content} onSubmit={function (_id, _title, _desc) {  // getReadContent()로부터 data로 주입시켜준다.
        var _contents = Array.from(this.state.contents) // contents를 복제한 _contents배열 생성
        var i = 0;
        while (i < _contents.length) {                  // _contents 배열만큼 반복
          if (_contents[i].id === _id) {                // _contents의 i번째 요소가 전달받은 _id와 같을 경우
            _contents[i] = { id: _id, title: _title, desc: _desc }  // _contents[i]에 id, title, desc를 교체입력
            break;
          }
          i = i + 1;
        }
        this.setState({
          contents: _contents,
          mode: 'read'  // 수정한 다음에는 자동으로 read모드가 되도록
        })
      }.bind(this)}></UpdateContent>
    }
    return _article;
  }
  render() {

    return (
      <div className="App">
        <Subject
          title={this.state.subject.title}
          sub={this.state.subject.sub}
          onChangePage={function () {
            this.setState({ mode: 'welcome' });
          }.bind(this)}
        />

        <TOC
          onChangePage={function (id) {
            this.setState({
              mode: 'read',
              selected_content_id: Number(id)
            });
          }.bind(this)}
          data={this.state.contents} />

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

        {this.getContent()} {/*getContent로부너 _article 변수 입력 */}
      </div>
    );
  }
}


export default App;
반응형

'Programming > Javascript' 카테고리의 다른 글

React강좌2, 전화번호부 - 1.Search기능  (0) 2020.08.01
React기초- 9.Delete  (0) 2020.07.29
React기초- 7.Create  (0) 2020.07.29
React기초- 6.이벤트  (0) 2020.07.28
React기초-5.state2  (0) 2020.07.27

댓글