Web/React & Next.js

React | State & Props & Event

일렁이는코드 2021. 10. 31. 17:46
Props
Props & event
State
Event & setState

Props 

props는 컴포넌트의 속성값으로 부모 컴포넌트로부터 전달 받은 데이터를 지니고 있는 객체입니다. 부모 컴포넌트로부터 자식 컴포넌트에게 state의 상태값, event handler를 넘겨줄 수 있습니다.

 

Props 객체

//Parent.js

import React from 'react';
import Child from '../pages/Child/Child';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
        <Child titleColor={this.state.color}/>
      </div>
    );
  }
}

export default State;

위 코드는 부모 컴포넌트의 코드이며, 자식 컴포넌트의 props로 titleColor 속성을 생성해주었고 부모 컴포넌트의 state 객체 중 color 값을 전달해주었습니다. 

 

//Child.js

import React from 'react';

class Child extends React.Component {
  render() {
		// console.log(this.props);

    return (
      <div>
        <h1 style={{color : this.props.titleColor}}>Child Component</h1>
      </div>
    );
  }
}

export default State;

<h1> 태그의 글자 색상을 부모 컴포넌트의 state로부터 전달 받은 데이터를 지정해주는 코드입니다. 

this.props 값의 결과 확인 시 props 객체 안에 부모로부터 전달받은 데이터가 key-value 형태로 담겨 있습니다. 

 

<h1 style={{color : this.props.titleColor}}>Child Component</h1>
  • this: 해당 컴포넌트
  • this.props : 해당 컴포넌트의 props 객체
  • this.props.titleColor: props 객체의 특정 key(titleColor)값. 즉 "red"

 

Props 예제

//index.js 
import React from 'react';
import ReactDOM from 'react-dom';
import Parent from './pages/App/Parent';

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

export default Parent;
//Parents.js
import React from 'react';
import Child from "./Child";

class Parent extends React.Component{
    render(){
        return(
            <div>
                <Child name="Alice" age={100} isMale={false} /><br/>
                <Child name="Sarah" age={50} isMale={false} /><br/>
                <Child name="James" age={20} isMale={true} /><br/>
            </div>
        );
    }
}

export default Parent;
//Child.js
import React from 'react';

class Child extends React.Component{
    render(){
        const { name, age, isMale } = this.props;
        return(
            <div>
                제 이름은 {name}이고 나이는 {age}이며 성별은 {isMale ? "남자" : "여자"}입니다.
            </div>
        );
    }
}

export default Child;

 

Props & event

// Parent.js

import React from 'react';
import Child from '../pages/Children/Children';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }

  handleColor = () => {
    this.setState({
      color: 'blue'
    })
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
        <Child titleColor={this.state.color} changeColor={this.handleColor}/>
      </div>
    );
  }
}

export default State;

 

// Child.js

import React from 'react';

class Child extends React.Component {
  render() {
		// console.log(this.props);

    return (
      <div>
        <h1 style={{color : this.props.titleColor}}>Child Component</h1>
				<button onClick={this.props.changeColor}>Click</button>
      </div>
    );
  }
}

export default State;

<button> 요소에서 onClick 이벤트 발생

➡️ 이벤트 발생시 this.props.changeColor 실행

➡️ handleColor 함수 실행시 setState 함수 호출

➡️ render 함수 호출

➡️ <Child /> 컴포넌트에 변경된 state 데이터 (this.state.color)전달.

 

 

Props Event 예제

//Parents.js
import React from 'react';
import Child from "./Child";

class Parent extends React.Component{
    handleClick = () => {
        alert("클릭!");
    };

    render(){
        return(
            <div>
                <Child name="Alice" age={100} isMale={false} handleClick={this.handleClick}/><br/>
                <Child name="Sarah" age={50} isMale={false} /><br/>
                <Child name="James" age={20} isMale={true} /><br/>
            </div>
        );
    }
}

export default Parent;
//Child.js
import React from 'react';

class Child extends React.Component{
    render(){
        const { name, age, isMale, handleClick } = this.props;
        return(
            <div onClick={handleClick}>
                제 이름은 {name}이고 나이는 {age}이며 성별은 {isMale ? "남자" : "여자"}입니다.
            </div>
        );
    }
}

export default Child;

 

State

State는 컴포넌트 내부에서 가지고 있는 컴포넌트의 상태값이며, 화면에 보여줄 컴포넌트의 UI 정보(상태)를 지니고 있는 객체입니다.
state에서 상태값을 설정하는 이유는 결국 컴포넌트 안의 요소에서 그 상태값을 반영하여 데이터가 바뀔때마다 효율적으로 화면에 나타내기 위해 사용합니다.

 

State 객체 (Class component)

import React from 'react';

class State extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }

  render() {
    return (
      <div>
        <h1 style={{ color: this.state.color  }}>Class Component | State</h1>
      </div>
    );
  }
}

export default State;
  • 화면에 나타내고 싶은 요소는 render() 안에 return()과 함께 적어줍니다. 
  • constructor 함수는 컴포넌트 선언문과 render함수 사이에 작성을 합니다.
  • comstructor 메소드 안에는 super()를 호출하고 this.state 값에 컴포넌트의 초기 상태값을 설정해 줍니다. 

 

state 예제 : 버튼을 누르면 색이 바뀌게 설정.

//Parents.js
import React from 'react';
import Child from "./Child";

class Parent extends React.Component{
    render(){
        return(
            <Child/>
        );
    }
}

export default Parent;

 

//Child.js
import React from 'react';

class Child extends React.Component{
    constructor() {
        super();

        this.state={
            titleColor: "Pink",
        };
    }

    changeColor = () =>{
        this.setState({
            titleColor:"blue",
        });
    }

    render(){
        return(
            <>
            <h1 style={{color:this.state.titleColor}}>state color 예제 </h1>
            <button onClick={this.changeColor}>Change Color</button>
            </>
        );
    }
}

export default Child;

 

Event & setState

import React, { Component } from 'react';

class State extends Component {
  constructor() {
    super();
    this.state = {
      color: 'red',
    };
  }

  handleColor = () => {
    this.setState({
      color: 'blue'
    })
  }

  render() {
    return (
      <div>
        <h1 style={{ color: this.state.color }}>Class Component | State</h1>
        <button onClick={this.handleColor}>Click</button>
      </div>
    );
  }
}

export default State;

<button> 요소에서 onClick 이벤트 발생

➡️ 현재 컴포넌트 (State)의 handleColor 함수 실행

➡️ handleColor 함수 실행시 setState 합수 실행

➡️ render 함수 호출

반응형