본문 바로가기
dev/React

[React18] props

by dev_Step 2023. 1. 11.

컴포넌트에서 전달되는 속성은  props로 전달된다.

 

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

 

Comment 컴포넌트를 더 작은 컴포넌트로 쪼개어 보자

 

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

위에서보면 props.author.avatarUrl 로 표현한 것을 볼수 있는데

Avatar 컴포넌트를 쪼개어 놓은 것에서는 props.user.avatarUrl 으로 표현 하였다.

그 이유는 props의 이름은 사용될 context가 아닌 컴포넌트 자체의 관점에서 변경하여 상요하는것을 권장한다.

 

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <Avatar user={props.author} />   // 여기서는 author로 표현한 이유는 Comment 컴포넌트에서 직접 받기 떄문이다.
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
      <div className="Comment-text">
        {props.text}
      </div>
      <div className="Comment-date">
        {formatDate(props.date)}
      </div>
    </div>
  );
}

Avatar 컴포넌트를 갖고 있는 UserInfo 컴포넌트를 다시 쪼개보자

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

 

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>
  );
}

 

 

const comment = {
  date: new Date(),
  text: 'I hope you enjoy learning React!',
  author: {
    name: 'Hello Kitty',
    avatarUrl: 'http://placekitten.com/g/64/64'
  }
};

 

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Comment
    date={comment.date}
    text={comment.text}
    author={comment.author} />
);

 

Commnet 태그에 props로 전달되는 것들은

date, text, author 가 되면 해당 props에는

commnet 객체의   comment.date, commnet.text, comment.author 가 전달되게 된다.

 

그래서 <Commnet>  컴포넌트에서 date, text, author를  그안쪽 컴포넌트에서

props.date,  props.text, props.author로 사용하는 것을 볼수 있다.

'dev > React' 카테고리의 다른 글

[React18] 조건부 렌더링  (0) 2023.01.21
[React18] setState()  (0) 2023.01.17
[React18] 엘리먼트 렌더링  (0) 2022.12.11
[React] 외부 데이터 사용  (0) 2022.12.02
[React] DOM 엘리먼트 접근  (0) 2022.12.01