React 기초정리 (Components)

박지성 학부생·2023년 1월 6일
1

FrontEnd Develop log

목록 보기
9/12

Component란?


React 기초정리(클릭)

  • 컴포넌트는 컴퓨터 소프트웨어에 있어서, 다시 사용할 수 있는 범용성을 위해 개발된 소프트웨어 구성 요소를 일컫는다.
  • 리액트에서 컴포넌트는 class형, function형으로 나뉜다. 개념적으로 컴포넌트는 JavaScript 함수와 유사하다. “props”라고 하는 임의의 입력을 받은 후, 화면에 어떻게 표시되는지를 기술하는 React 엘리먼트를 반환한다.
    //class형
    
    class Welcome extends React.Component {
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }
    
    //function 형
    
    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
  • 컴포넌트가 재사용성과 범용성을 가지기 위해서는 딱 한 가지의 역할만 수행시키기를 권장한다. (객체지향 : 단일 책임 원칙) 리액트 컴포넌트는 단순하게 보면 props를 받아서 DOM 렌더를 시키는 JSX를 리턴하는 함수이다. 동일한 props를 받으면 같은 JSX를 리턴하는 순수함수로 이뤄져야 한다.

Component 랜더링

function User(props){
  return <h1> Welcome ! {props.user} </h1>
}
const element= <User user="eunsu" />
const rootElement = document.getElementById("root");

ReactDOM.render(
   element, rootElement
);
  • <User user="eunsu" /> 엘리먼트로 ReactDOM.render()호출{user:eunsu} props로 전달 User function 호출User함수의 반환값으로 <h1>Welcome! eunsu</h1> 반환 React.DOM에 랜더링되서 index.html에 출력

컴포넌트에서 다른 컴포넌트를 담기

  • 경우에 따라 특정 컴포넌트들은 어떤 자식 엘리먼트가 들어올 지 미리 예상할 수 없다. 그럴경우 props.children을 사용해서 children의 내용을 처리 할 수 있다.
    function Children1() {
        return (
          <div className="children1">
            <div>2</div>
          </div>
        );
      }
      function Children2() {
        return (
          <div>
            <div>3</div>
          </div>
        );
      }
      function Children3() {
        return (
          <div>
            <div>4</div>
          </div>
        );
      }
    function Parents(children){
    	return(
        <div>
          <div>1</div>
          {children}
          <div>5</div>
         </div>
        )
    }
    exports default function App(){
    	return(
        	<Parents>
          		<p>3</p>
          	<Parents>
        )
    }
  • 컴포넌트를 참조해서 무언가를 처리하려고 할 때, 사용하면 된다.
    *Box.jsx
    import BoxItems from "./BoxItems";
    export default function Box() {
      const user = [
        {
          name: "Judy",
          age: 15,
          gender: "female"
        },
        {
          name: "Holy",
          age: 23,
          gender: "male"
        }
      ];
      return (
        <>
          <BoxItems>
            {user.map((item) => (
              <>
                <p>Name: {item.name} </p>
                <p> Age: {item.age} </p>
              </>
            ))}
          </BoxItems>
        </>
      );
    }
    *BoxItems.jsx
    const BoxItems= ({children}) => {
      return (
        <div>
          <h1>Welcome to World!</h1>
          {children}
        </div>
      )
    }
    export default BoxItems;
    • 자식컴포넌트인 BoxItems.jsx에서 처리할 일들을 {children} 처리를 해주고, 그 일을 부모컴포넌트인 Box.jsx에서 처리해 준다. 하지만 이건 상속이 아닌 합성이다.
      • 그 이유는 props를 전달하는 것이 아니라, 부모 컴포넌트에서 처리 하는 것이기 때문이다.
profile
참 되게 살자

0개의 댓글