React 기초

Clém·2021년 1월 15일
0
post-thumbnail

React 는?

  • 선언형 : 상호작용이 많은 ui를 만들 때 생기는 어려움을 줄어준다.
    (데이터가 변경됨에 따라 적절한 컴포넌트만 효율적으로 갱신하고 렌더링한다.)
  • 컴포넌트 기반 : 컴포넌트 로직은 template이 아닌 JavaScript로 작성되어 데이터를 손쉽게 전달 할 수 있다. DOM과는 별개로 상태를 관리한다.

Simple component

React 컴포넌트는 render()라는 메소드를 구현하는데, 입력값을 받아 화면에 표시하는 내용을 반환한다. 컴포넌트로 전달될 데이터는 render() 안에서 this.props를 통해 접근한다.

class Greeting extends React.Component {
  render() {
    return (
      <div>
        Hello {this.props.name} //전달된 데이터는 this.props.를 통해 접근한다
      </div>
    );
  }
}
//컴포넌트는 render() 메소드를 구현한다
ReactDOM.render(
  <Greeting name="Taylor" />, //name은 데이터로 전달되고 
  document.getElementById('Greeting-example') //id를 찾아간다
);

component with state

컴포넌트는 this.props를 통해 내부적인 상태 데이터를 가질 수 있다. this.state로 접근한다. 상태가 바뀌면 render() 메소드가 다시 호출되어 마크업이 갱신된다.

class Timer extends React.Component {
  constructor(props) { //생성자
    super(props); //부모클래스 생성자를 참조, super()를 호출해야 this를 쓸 수 있다
    this.state = { seconds: 0 };
  }

  tick() {
    this.setState(state => ({ //setState : 상태를 업데이트한다 
      seconds: state.seconds + 1
    }));
  }

  componentDidMount() { //render 전 mount됬을 때 
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() { //unmount 될 때 
    clearInterval(this.interval);
  }

  render() {
    return (
      <div>
        Seconds: {this.state.seconds}
      </div>
    );
  }
}

ReactDOM.render(
  <Timer />,
  document.getElementById('timer-example')
);

*이해하기 어려운 부분이다(lifecycle에 대해 더 알아보자)

application

props와 state를 사용하여 간단한 ToDo application을 만들 수 있다.

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items: [], text: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  render() {
    return (
      <div>
        <h3>TODO</h3>
        <TodoList items={this.state.items} /> 
        <form onSubmit={this.handleSubmit}>
          <label htmlFor="new-todo">
            What needs to be done?
          </label>
          <input
            id="new-todo"
            onChange={this.handleChange}
            value={this.state.text}
          />
          <button>
            Add #{this.state.items.length + 1}
          </button>
        </form>
      </div>
    );
  }

  handleChange(e) {
    this.setState({ text: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault(); //페이지 이동, form안의 input전송동작 중단
    if (this.state.text.length === 0) {
      return;
    }
    const newItem = {
      text: this.state.text, //text정의
      id: Date.now() //id부여 
    };
    this.setState(state => ({
      items: state.items.concat(newItem), //concat 배열을 합친다
      text: '' //text는 빈값으로 
    }));
  }
}

class TodoList extends React.Component {
  render() {
    return (
      <ul> //map을 통해 뿌려준다
        {this.props.items.map(item => (
          <li key={item.id}>{item.text}</li>
        ))}
      </ul>
    );
  }
}

ReactDOM.render(
  <TodoApp />,
  document.getElementById('todos-example')
);

component that uses plugin of outside

class MarkdownEditor extends React.Component {
  constructor(props) { //생성자
    super(props);
    this.md = new Remarkable(); //remarable 객체 인스턴스
    this.handleChange = this.handleChange.bind(this);
    this.state = { value: 'Hello, **world**!' }; //초기값
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  getRawMarkup() {
    return { __html: this.md.render(this.state.value) };
  }

  render() {
    return (
      <div className="MarkdownEditor">
        <h3>Input</h3>
        <label htmlFor="markdown-content">
          Enter some markdown
        </label>
        <textarea
          id="markdown-content"
          onChange={this.handleChange}
          defaultValue={this.state.value}
        />
        <h3>Output</h3>
        <div
          className="content"
          dangerouslySetInnerHTML={this.getRawMarkup()}
        />
      </div>
    );
  }
}

ReactDOM.render(
  <MarkdownEditor />,
  document.getElementById('markdown-example')
);

위 내용은 React 공식 홈페이지를 참고하였다.
React 바로가기

profile
On my way to become a Web Publisher

0개의 댓글