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>
  );
}
๋ฐ˜์‘ํ˜•