Framwork & Library/ReactJS

Components와 Props

junnnhhh 2024. 2. 21. 22:34
728x90

https://ko.legacy.reactjs.org/docs/components-and-props.html

 

Components와 Props – React

A JavaScript library for building user interfaces

ko.legacy.reactjs.org

Component는 React Element를 생성하기 위해 쓰이는 틀이다.

 

Component를 통해 UI를 재사용 가능한 여러 조각으로 나누고, 각 조각을 사용할 수 있다. (Component 추출)

Component는 props라는 속성을 사용하여 다른 엘리먼트를 만들어 낼 수 있다.

 

Component의 종류

Function Component

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

Class Component (ES6 문법)

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

 

Component Rendering

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

const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />; // props.name = "Sara"
root.render(element);
  1. Welcome이란 Function Component를 구현한다.
  2. element 변수에 Welcome Component의 props.name = "Sara"를 주고 엘리먼트를 생성한다.
  3. 생성한 엘리먼트를 렌더링한다.

Component 합성

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

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

※ Component의 이름은 항상 대문자로 시작해야 한다.
    소문자로 시작할 경우, DOM 태그 (div, span, ... ) 로 인식을 하기 때문이다.

 

※ props는 읽기 전용이기 때문에 Component(Function or Class) 내부에서 입력 받은 props 자체의 값을 수정하면 안된다. 이를 순수 함수라고 한다.

ex) 순수 함수

function sum(a, b) {
  return a + b;
}

ex) 일반 함수

function withdraw(account, amount) {
  account.total -= amount;
}
728x90

'Framwork & Library > ReactJS' 카테고리의 다른 글

Element Rendering  (2) 2024.02.20
JSX란?  (0) 2024.02.19