component, props

VeryverySoHappy·2024년 10월 12일
post-thumbnail

Component

  • 사용하는 이유 / 특징
    1. 재사용 가능한 UI 구성 요소를 만들 수 있다.
    2. UI의 모든 부분은 component
    3. 다음을 제외하고 일반 JS 함수
      1. 이름은 항상 대문자
      2. JSX 마크업을 반환
  • 함수형 component
    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
  • class형 component
    class Welcome extends React.Component {
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }
  • 주의
    1. 대문자로 작성하기

      그렇지 않으면 작동x

    2. return ( ) → 괄호가 있어야 됌

    3. 컴포넌트는 다른 컴포넌트를 렌더링 할 수 있지만 중첩하면 x

      → 매우 느리고 버그를 일으킴

      export default function Gallery() {
        // 🔴 Never define a component inside another component!
        function Profile() {
          // ...
        }
        // ...
      }
      export default function Gallery() {
        // ...
      }
      
      // ✅ Declare components at the top level
      function Profile() {
        // ...
      }

props

이름은 사용될 context가 아닌 컴포넌트 자체의 관점에서 짓기!

  • 사용하는 이유 하위 component에 넘겨주고싶은 값이 있을 때 사용
  • 예시
    • 사용 방법
      function Welcome(props) {
        return <h1>Hello, {props.name}</h1>;
      }
      
      function App(props) {
        return(
          <>
            <Welcome name="Sara"/>
            <Welcome name="Cahal"/>
            <Welcome name="Edite"/>
          </>
        )
      }
      
      export default App;
    • props (객체, 문자열, 날짜)를 props를 받는 방법 author 객체, text 문자열, date 날짜 formatDate = props를 함수로 감싸주기
      import React from 'react'
      
      function formatDate(date) {
        return date.toLocaleDateString();
      }
      
      const comment ={
        date: new Date(),
        text: 'hihihi',
        author: {
          name: 'Hello Kitty',
          avataUrl: 'http://placekitten.com/g/64/64'
        }
      };
      
      function Comment(props) {
        return (
          <div>
            <div>
              <img 
                src={props.author.avataUrl}
                alt={props.author.name}
              />
              <div>
                {props.author.name}
              </div>
            </div>
            <div>{props.text}</div>
            <div>{formatDate(props.date)}</div>
          </div>
        )
      }
      
      function App() {
        return (
          <Comment
            date={comment.date}
            text={comment.text}
            author={comment.author}
          />
        )
      }
      
      export default App
      • component를 나눈 코드

        import React from 'react'
        
        function formatDate(date) {
          return date.toLocaleDateString();
        }
        
        const comment ={
          date: new Date(),
          text: 'hihihi',
          author: {
            name: 'Hello Kitty',
            avataUrl: 'http://placekitten.com/g/64/64'
          }
        };
        
        function Avatar(props) {
          return (
            <img className="Avatar"
              src={props.user.avataUrl}
              // Comment 내에서 렌더링 된다는 것을 알 필요가 없음
              // 따라서 props의 이름을 author에서 더욱 일반화된 user로 변경
              // 이름은 사용될 context가 아닌 컴포넌트 자체의 관점에서 짓기!
              alt={props.user.name}
            />
          )
        }
        
        function UserInfo(props) {
          return (
            <div className="UserInfo">
              <Avatar/>
              <div className="UserInfo-name">
                {props.user.name}
              </div>
            </div>
          )
        }
        
        function Comment(props) {
          return (
            <div>
              <UserInfo user={props.author}/>
              <div className="Comment-text">
                {props.text}
              </div>
              <div className="Comment-date">
                {formatDate(props.date)}
              </div>
            </div>
          )
        }
        
        function App() {
          return (
            <Comment
              date={comment.date}
              text={comment.text}
              author={comment.author}
            />
          )
        }
        
        export default App
  • 주의 사항 순수 함수로 사용하기
    function sum(a, b) {
    	return a + b; 
    } 
    // 순수 함수
    자신의 입력 값을 변경하기 때문에 순수 함수 x

0개의 댓글