Frontend/React

React | Props (속성), State (μƒνƒœ) 에 λŒ€ν•΄μ„œ

이제희 2023. 11. 17. 17:00


Props (속성)

  • λΆ€λͺ¨ -> μžμ‹ μ»΄ν¬λ„ŒνŠΈλ‘œ 데이터λ₯Ό 전달할 λ•Œ μ‚¬μš©ν•œλ‹€.
  • 읽기 μ „μš©μ΄λ©°, μžμ‹ μ»΄ν¬λ„ŒνŠΈμ—μ„œ μˆ˜μ •ν•  수 μ—†λ‹€.
// λΆ€λͺ¨ μ»΄ν¬λ„ŒνŠΈ
import React from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const data = "전달할 데이터";
  return <ChildComponent data={data} />;
};

// μžμ‹ μ»΄ν¬λ„ŒνŠΈ
import React from 'react';

const ChildComponent = (props) => {
  return <div>{props.data}</div>;
};

State (μƒνƒœ)

  • μ»΄ν¬λ„ŒνŠΈ λ‚΄λΆ€μ—μ„œ 관리 ν•˜λŠ” 데이터이닀.
  • μ»΄ν¬λ„ŒνŠΈμ˜ μƒνƒœκ°€ λ³€ν™”ν•  λ•Œλ§ˆλ‹€ ReactλŠ” μžλ™μœΌλ‘œ λžœλ”λ§ν•œλ‹€.
  • State의 μ΄ˆκΈ°ν™”λŠ” μ»΄ν¬λ„ŒνŠΈμ˜ constructorμ—μ„œ μˆ˜ν–‰ν•œλ‹€.
  • State λ³€κ²½ μ‹œ, Stateλ₯Ό 직접 μˆ˜μ •ν•΄μ„œλŠ” μ•ˆλ˜κ³ , SetState λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ 변경을 λ°˜μ˜ν•œλ‹€.
  • ν΄λž˜μŠ€ν˜• μ»΄ν¬λ„ŒνŠΈμ—μ„œλŠ” this.State둜 State에 μ ‘κ·Όν•˜κ³ , ν•¨μˆ˜ν˜• μ»΄ν¬λ„ŒνŠΈμ—μ„œλŠ” useState 훅을 μ‚¬μš©ν•œλ‹€.
// ν΄λž˜μŠ€ν˜• μ»΄ν¬λ„ŒνŠΈμ—μ„œμ˜ state
import React, { Component } from 'react';

class ExampleComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}
// ν•¨μˆ˜ν˜• μ»΄ν¬λ„ŒνŠΈμ—μ„œμ˜ state
import React, { useState } from 'react';

const ExampleComponent = () => {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}
λ°˜μ‘ν˜•