TIL 13 - React (Component and Props)

chachacha·2021년 4월 25일
0

React

목록 보기
2/8
post-thumbnail

Component는 재사용 가능한 UI 단위입니다. 컴포넌트는 독립적으로 재사용가능한 코드로 관리할 수 있습니다.

Component is very similar to function 컴포넌트는 input을 받아서 return 할 수 있습니다. 리엑트 컴포넌트에서는 inputprops라고 말하고 return은 화면에 보여져야할 리엑트 요소가 return됩니다.

Component 만들기

React는 컴포넌트를 class나 함수로 만들 수 있습니다. 어떤 때에는 함수로 컴포넌트를 만들면 좋고 그리고 어떤때는 class로 만들면 좋습니다.

함수로 Welcome 컴포넌트 구현하기

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

class로 Welcome 컴포넌트 구현하기

class로 컴포넌트를 만드려면 React.Component를 extend해서 생성해야합니다. 생성할 때는 `render() 메서드는 무저건 정의해야하고, 'return도 해주어야 합니다.

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

Component 사용의 예

// 1. Welcome 컴포넌트 정의
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
// 2. App 컴포넌트 정의
function App() {
  return (
    <div>
    	<Welcome name="Sara" />
    	<Welcome name="Cahal" />
    	<Welcome name="Edite" />
   	</div>
  );
}
// 3. 화면에 React 요소 그려주기
ReactDOM.render(
  <App />,
  document.getElementById('root')
);

더 작은 Component로 분리하기

아래는 Comment라는 컴포넌트입니다. 컴포넌트는 재사용 가능한 코드 단위입니다. 밑에 example에서 .avatar 요소를 컴포넌트로 만들었습니다. .avatar는 댓글창 이외에도 사용자정보 등 여기저기에 많이 쓰일 수 있습니다.

function Comment(props) {
  return (
    <div className="comment">
      <div className="user-info">
        <img className="avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="user-info-name">
          {props.author.name}
        </div>
      </div>
      <div className="comment-text">
        {props.text}
      </div>
      <div className="comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

props.user에서 avatarUrl, name 값을 가져오도록 하겠습니다. <Avatar />를 사용하는 측에서 user라는 attribute를 추가해야겠네요.

function Avatar(props) {
  return (
    <img className = "avatar"
    	src = {props.user.avatarUrl}
		alt = {props.user.name}
	/>
  );
}

Avatar 컴포넌트에서 user의 avatarUrl과 name이 필요하므로, Comment 컴포넌트에서 props.author정보를 user라는 attribute로 넘겨주었습니다.

function Comment(props) {
  return (
    <div className = "comment">
    	<div className = "user-info">
    		<Avatar user = {props.author} />
			<div className = "user-info-name">
              {props.author.name}
			</div>
		</div>
		<div className = "comment-text">
          {formatDate(props.date)}
        </div>
      </div>
   );
}

재사용할 가능성이 있기 때문에 .user-info 부분을 컴포넌트로 만들어 보겠습니다.

function UserInfo(props) {
  return (
    <div className = "user-info">
    	<Avatar user = {props.user} />
		<div className = "user-info-name">
          {props.user.name}
		</div>
	</div>
  );
}

이렇게 하면 Comment 컴포넌트는 이제 엄청나게 간결해졌습니다.

function Comment(props) {
  return (
    <div className = "comment">
    	<UserInfo user = {props.author} />
		<div className = "comment-text">
          {props.text}
		</div>
		<div className = "comment-date">
          {formatDate(props.date)}
        </div>
     </div>
  );
}

0개의 댓글