ksy0314 2020. 10. 6. 11:55

1. JSX

컴포넌트라는 유닛을 통해 html element의 유지관리를 할 수 있고
이 기능을 자바스크립트에 추가한것

 

let name = '김상연'

const element = <h1>Hello, {name}</h1>;

let name = '김상연'
const element = <h1>Hello, {name}</h1>;

이처럼 JSX 안에서 표현식을 사용할수 있다.
여러줄로 나눠서 쓰려면 괄호로 묶어야 세미콜론 삽입을 피할 수 있다.

 

속성에 따옴표를 이용해 문자열 리터럴을 정의할 수 있습니다.

const element = <div tabIndex="0"></div>

const element = <div tabIndex="0"></div>

 

속성에 표현식 삽입도 가능

const element = <div tabIndex={user.tabindex}></div>

const element = <div tabIndex={user.tabindex}></div>

JSX 태그는 자식을 포함할 수 있음

const element = (<div>

    <h1>hello!</h1>

</div>);

const element = (
	<div>
    	<h1>hello!</h1>
      </div>
);

 

 

2. 엘리먼트 렌더링

기본 렌더링 방법

const element = <h1>Hello, world</h1>;

ReactDOM.render(element, document.getElementById('root'));

 

3. Component와 Props

 

함수 컴포넌트

function Welcome(props)

  { return <h1>Hello, {props.name}</h1>;

}

function Welcome(props){
	return <h1>Hello, {props.name}</h1>;
}

 

클래스 컴포넌트

 

class Welcome extends React.Component {

   render() {

      return <h1>Hello, {this.props.name}</h1>;

   }

}

class Welcome extends React.Component {
	render() {
    	return <h1>Hello, {this.props.name}</h1>;
    }
}

 

컴포넌트 렌더링

 

const element = <Welcome name="Sara" />;

ReactDOM.render(

   element,

   document.getElementById('root')

);

const element = <Welcome name="Sara" />;
ReactDOM.render(element,document.getElementById('root'));

 

4. State와 생명주기

Clock이 추가될때 setInterval을 실행시켜주고

제거 될때 종료시켜준다. (생명주기 관리)

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

state 특징

 

*직접 state 수정 금지

// Wrong
this.state.comment = 'Hello';
// Correct
this.setState({comment: 'Hello'});

*state는 비동기적일 수 있음

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});
// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

 

 

5. 이벤트 처리하기

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // 콜백에서 `this`가 작동하려면 아래와 같이 바인딩 해주어야 합니다.
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

class의 매소드는 바인드를 해줘야 잘 연결됨

 

 

6. 조건부 렌더링